~ chicken-core (chicken-5) /manual/Module scheme


   1[[tags: manual]]
   2[[toc:]]
   3
   4== Module scheme
   5
   6This module provides all of CHICKEN's R5RS procedures and macros.
   7These descriptions are based directly on the ''Revised^5 Report on the
   8Algorithmic Language Scheme''.
   9
  10This module is used by default, unless a program is compiled with
  11the {{-explicit-use}} option.
  12
  13== Expressions
  14
  15Expression types are categorized as primitive or derived. Primitive
  16expression types include variables and procedure calls. Derived
  17expression types are not semantically primitive, but can instead be
  18defined as macros. With the exception of quasiquote, whose macro
  19definition is complex, the derived expressions are classified as
  20library features.  The distinction which R5RS makes between primitive
  21and derived is unimportant and does not necessarily reflect how it's
  22implemented in CHICKEN itself.
  23
  24=== Primitive expression types
  25
  26==== Variable references
  27
  28<macro><variable></macro><br>
  29
  30An expression consisting of a variable is a variable reference. The
  31value of the variable reference is the value stored in the location to
  32which the variable is bound. It is an error to reference an unbound
  33variable.
  34
  35 (define x 28)
  36 x           ===>  28
  37
  38==== Literal expressions
  39
  40<macro>(quote <datum>)</macro><br>
  41<macro>'<datum></macro><br>
  42<macro><constant></macro><br>
  43
  44(quote <datum>) evaluates to <datum>. <Datum> may be any external
  45representation of a Scheme object. This notation is used to include
  46literal constants in Scheme code.
  47
  48 (quote a)                    ===>  a
  49 (quote #(a b c))             ===>  #(a b c)
  50 (quote (+ 1 2))              ===>  (+ 1 2)
  51
  52(quote <datum>) may be abbreviated as '<datum>. The two notations are
  53equivalent in all respects.
  54
  55 'a                           ===>  a
  56 '#(a b c)                    ===>  #(a b c)
  57 '()                          ===>  ()
  58 '(+ 1 2)                     ===>  (+ 1 2)
  59 '(quote a)                   ===>  (quote a)
  60 ''a                          ===>  (quote a)
  61
  62Numerical constants, string constants, character constants, and boolean
  63constants evaluate "to themselves"; they need not be quoted.
  64
  65 '"abc"             ===>  "abc"
  66 "abc"              ===>  "abc"
  67 '145932            ===>  145932
  68 145932             ===>  145932
  69 '#t                ===>  #t
  70 #t                 ===>  #t
  71
  72It is an error to alter a constant (i.e. the value of a literal
  73expression) using a mutation procedure like set-car! or string-set!.
  74In the current implementation of CHICKEN, identical constants don't
  75share memory and it is possible to mutate them, but this may change in
  76the future.
  77
  78==== Procedure calls
  79
  80<macro>(<operator> <operand[1]> ...)</macro><br>
  81
  82A procedure call is written by simply enclosing in parentheses
  83expressions for the procedure to be called and the arguments to be
  84passed to it. The operator and operand expressions are evaluated (in an
  85unspecified order) and the resulting procedure is passed the resulting
  86arguments.
  87
  88 (+ 3 4)                           ===>  7
  89 ((if #f + *) 3 4)                 ===>  12
  90
  91A number of procedures are available as the values of variables in the
  92initial environment; for example, the addition and multiplication
  93procedures in the above examples are the values of the variables + and
  94*.  New procedures are created by evaluating lambda
  95expressions. Procedure calls may return any number of values (see the
  96{{values}} procedure [[#Control_features|below]]).
  97
  98Procedure calls are also called combinations.
  99
 100Note:   In contrast to other dialects of Lisp, the order of
 101evaluation is unspecified, and the operator expression and the
 102operand expressions are always evaluated with the same evaluation
 103rules.
 104
 105Note:   Although the order of evaluation is otherwise unspecified,
 106the effect of any concurrent evaluation of the operator and operand
 107expressions is constrained to be consistent with some sequential
 108order of evaluation. The order of evaluation may be chosen
 109differently for each procedure call.
 110
 111Note:   In many dialects of Lisp, the empty combination, (), is a
 112legitimate expression. In Scheme, combinations must have at least
 113one subexpression, so () is not a syntactically valid expression.
 114
 115==== Procedures
 116
 117<macro>(lambda <formals> <body>)</macro><br>
 118
 119Syntax: <Formals> should be a formal arguments list as described below,
 120and <body> should be a sequence of one or more expressions.
 121
 122Semantics: A lambda expression evaluates to a procedure. The
 123environment in effect when the lambda expression was evaluated is
 124remembered as part of the procedure. When the procedure is later called
 125with some actual arguments, the environment in which the lambda
 126expression was evaluated will be extended by binding the variables in
 127the formal argument list to fresh locations, the corresponding actual
 128argument values will be stored in those locations, and the expressions
 129in the body of the lambda expression will be evaluated sequentially in
 130the extended environment. The result(s) of the last expression in the
 131body will be returned as the result(s) of the procedure call.
 132
 133 (lambda (x) (+ x x))              ===>  a procedure
 134 ((lambda (x) (+ x x)) 4)          ===>  8
 135 
 136 (define reverse-subtract
 137   (lambda (x y) (- y x)))
 138 (reverse-subtract 7 10)           ===>  3
 139 
 140 (define add4
 141   (let ((x 4))
 142     (lambda (y) (+ x y))))
 143 (add4 6)                          ===>  10
 144
 145<Formals> should have one of the following forms:
 146
 147*   (<variable[1]> ...): The procedure takes a fixed number of
 148    arguments; when the procedure is called, the arguments will be
 149    stored in the bindings of the corresponding variables.
 150
 151*   <variable>: The procedure takes any number of arguments; when the
 152    procedure is called, the sequence of actual arguments is converted
 153    into a newly allocated list, and the list is stored in the binding
 154    of the <variable>.
 155
 156*   (<variable[1]> ... <variable[n]> . <variable[n+1]>): If a
 157    space-delimited period precedes the last variable, then the
 158    procedure takes n or more arguments, where n is the number of
 159    formal arguments before the period (there must be at least one).
 160    The value stored in the binding of the last variable will be a
 161    newly allocated list of the actual arguments left over after all
 162    the other actual arguments have been matched up against the other
 163    formal arguments.
 164
 165It is an error for a <variable> to appear more than once in <formals>.
 166
 167 ((lambda x x) 3 4 5 6)                  ===>  (3 4 5 6)
 168 ((lambda (x y . z) z)
 169  3 4 5 6)                               ===>  (5 6)
 170
 171Each procedure created as the result of evaluating a lambda expression
 172is (conceptually) tagged with a storage location, in order to make eqv?
 173and eq? work on procedures.
 174
 175As an extension to R5RS, CHICKEN also supports "extended" DSSSL style
 176parameter lists, which allows embedded special keywords.  Such a
 177keyword gives a special meaning to the {{<formal>}} it precedes.
 178DSSSL parameter lists are defined by the following grammar:
 179
 180 <parameter-list> ==> <required-parameter>*
 181                      [#!optional <optional-parameter>*]
 182                      [#!rest <rest-parameter>]
 183                      [#!key <keyword-parameter>*]
 184 <required-parameter> ==> <ident>
 185 <optional-parameter> ==> <ident>
 186                          | (<ident> <initializer>)
 187 <rest-parameter> ==> <ident>
 188 <keyword-parameter> ==> <ident>
 189                         | (<ident> <initializer>)
 190 <initializer> ==> <expr>
 191
 192When a procedure is applied to a list of arguments, the parameters and arguments are processed from left to right as follows:
 193
 194* Required-parameters are bound to successive arguments starting with the first argument. It shall be an error if there are fewer arguments than required-parameters.
 195* Next, the optional-parameters are bound with the remaining arguments. If there are fewer arguments than optional-parameters, then the remaining optional-parameters are bound to the result of the evaluation of their corresponding <initializer>, if one was specified, otherwise {{#f}}. The corresponding <initializer> is evaluated in an environment in which all previous parameters have been bound.
 196* If there is a rest-parameter, then it is bound to a list containing all the remaining arguments left over after the argument bindings with required-parameters and optional-parameters have been made. 
 197* If {{#!key}} was specified in the parameter-list, there should be an even number of remaining arguments. These are interpreted as a series of pairs, where the first member of each pair is a keyword specifying the parameter name, and the second member is the corresponding value. If the same keyword occurs more than once in the list of arguments, then the corresponding value of the first keyword is the binding value. If there is no argument for a particular keyword-parameter, then the variable is bound to the result of evaluating <initializer>, if one was specified, otherwise {{#f}}. The corresponding <initializer> is evaluated in an environment in which all previous parameters have been bound. 
 198
 199Needing a special mention is the close relationship between the
 200rest-parameter and possible keyword-parameters.  Declaring a
 201rest-parameter binds up all remaining arguments in a list, as
 202described above. These same remaining arguments are also used for
 203attempted matches with declared keyword-parameters, as described
 204above, in which case a matching keyword-parameter binds to the
 205corresponding value argument at the same time that both the keyword
 206and value arguments are added to the rest parameter list.  Note that
 207for efficiency reasons, the keyword-parameter matching does nothing
 208more than simply attempt to match with pairs that may exist in the
 209remaining arguments.  Extra arguments that don't match are simply
 210unused and forgotten if no rest-parameter has been declared.  Because
 211of this, the caller of a procedure containing one or more
 212keyword-parameters cannot rely on any kind of system error to report
 213wrong keywords being passed in.
 214
 215It shall be an error for an {{<ident>}} to appear more than once in a
 216parameter-list.
 217
 218If there is no rest-parameter and no keyword-parameters in the parameter-list, then it shall be an error for any extra arguments to be passed to the procedure.
 219
 220
 221Example:
 222
 223 ((lambda x x) 3 4 5 6)       => (3 4 5 6)
 224 ((lambda (x y #!rest z) z)
 225  3 4 5 6)                    => (5 6)
 226 ((lambda (x y #!optional z #!rest r #!key i (j 1)) 
 227     (list x y z i: i j: j))
 228  3 4 5 i: 6 i: 7)            => (3 4 5 i: 6 j: 1)
 229
 230
 231
 232==== Conditionals
 233
 234<macro>(if <test> <consequent> <alternate>)</macro><br>
 235<macro>(if <test> <consequent>)</macro><br>
 236
 237Syntax: <Test>, <consequent>, and <alternate> may be arbitrary
 238expressions.
 239
 240Semantics: An if expression is evaluated as follows: first, <test> is
 241evaluated. If it yields a true value (see [[#Booleans|the section
 242about booleans]] below), then <consequent> is evaluated and its
 243value(s) is(are) returned. Otherwise <alternate> is evaluated and its
 244value(s) is(are) returned. If <test> yields a false value and no
 245<alternate> is specified, then the result of the expression is
 246unspecified.
 247
 248 (if (> 3 2) 'yes 'no)                   ===>  yes
 249 (if (> 2 3) 'yes 'no)                   ===>  no
 250 (if (> 3 2)
 251     (- 3 2)
 252     (+ 3 2))                            ===>  1
 253
 254==== Assignments
 255
 256<macro>(set! <variable> <expression>)</macro><br>
 257
 258<Expression> is evaluated, and the resulting value is stored in the
 259location to which <variable> is bound. <Variable> must be bound either
 260in some region enclosing the set! expression or at top level. The
 261result of the set! expression is unspecified.
 262
 263 (define x 2)
 264 (+ x 1)                         ===>  3
 265 (set! x 4)                      ===>  unspecified
 266 (+ x 1)                         ===>  5
 267
 268As an extension to R5RS, {{set!}} for unbound toplevel variables is
 269allowed.  Also, {{(set! (PROCEDURE ...) ...)}} is supported, as CHICKEN
 270implements [[http://srfi.schemers.org/srfi-17/srfi-17.html|SRFI-17]].
 271
 272=== Derived expression types
 273
 274The constructs in this section are hygienic.  For reference purposes,
 275these macro definitions will convert most of the constructs described
 276in this section into the primitive constructs described in the
 277previous section.  This does not necessarily mean that's exactly how
 278it's implemented in CHICKEN.
 279
 280==== Derived Conditionals
 281
 282<macro>(cond <clause[1]> <clause[2]> ...)</macro><br>
 283
 284Syntax: Each <clause> should be of the form
 285
 286 (<test> <expression[1]> ...)
 287
 288where <test> is any expression. Alternatively, a <clause> may be of the
 289form
 290
 291 (<test> => <expression>)
 292
 293The last <clause> may be an "else clause," which has the form
 294
 295 (else <expression[1]> <expression[2]> ...).
 296
 297Semantics: A cond expression is evaluated by evaluating the <test>
 298expressions of successive <clause>s in order until one of them
 299evaluates to a true value (see [[#Booleans|the section about
 300booleans]] below). When a <test> evaluates to a true value, then the
 301remaining <expression>s in its <clause> are evaluated in order, and
 302the result(s) of the last <expression> in the <clause> is(are)
 303returned as the result(s) of the entire cond expression. If the
 304selected <clause> contains only the <test> and no <expression>s, then
 305the value of the <test> is returned as the result.  If the selected
 306<clause> uses the => alternate form, then the <expression> is
 307evaluated. Its value must be a procedure that accepts one argument;
 308this procedure is then called on the value of the <test> and the
 309value(s) returned by this procedure is(are) returned by the cond
 310expression. If all <test>s evaluate to false values, and there is no
 311else clause, then the result of the conditional expression is
 312unspecified; if there is an else clause, then its <expression>s are
 313evaluated, and the value(s) of the last one is(are) returned.
 314
 315 (cond ((> 3 2) 'greater)
 316       ((< 3 2) 'less))           ===>  greater
 317 (cond ((> 3 3) 'greater)
 318       ((< 3 3) 'less)
 319       (else 'equal))             ===>  equal
 320 (cond ((assv 'b '((a 1) (b 2))) => cadr)
 321       (else #f))                 ===>  2
 322
 323
 324As an extension to R5RS, CHICKEN also supports the
 325[[http://srfi.schemers.org/srfi-61|SRFI-61]] syntax:
 326
 327 (<generator> <guard> => <expression>)
 328
 329In this situation, {{generator}} is ''always'' evaluated.  Its
 330resulting value(s) are used as argument(s) for the {{guard}}
 331procedure.  Finally, if {{guard}} returns a non-{{#f}} value, the
 332{{expression}} is evaluated by calling it with the result of
 333{{guard}}.  Otherwise, evaluation procedes to the next clause.
 334
 335<macro>(case <key> <clause[1]> <clause[2]> ...)</macro><br>
 336
 337Syntax: <Key> may be any expression. Each <clause> should have the form
 338
 339 ((<datum[1]> ...) <expression[1]> <expression[2]> ...),
 340
 341where each <datum> is an external representation of some object.
 342Alternatively, as per R7RS, a <clause> may be of the form
 343
 344 ((<datum[1]> ...) => <expression>).
 345
 346All the <datum>s must be distinct. The last <clause> may be an
 347"else clause," which has one of the following two forms:
 348
 349 (else <expression[1]> <expression[2]> ...)
 350 (else => <expression>).      ; R7RS extension
 351
 352Semantics: A case expression is evaluated as follows. <Key> is
 353evaluated and its result is compared against each <datum>. If the
 354result of evaluating <key> is equivalent (in the sense of {{eqv?}};
 355see [[#Equivalence_predicates|below]]) to a <datum>, then the
 356expressions in the corresponding <clause> are evaluated from left to
 357right and the result(s) of the last expression in the <clause> is(are)
 358returned as the result(s) of the case expression. If the selected
 359<clause> uses the => alternate form (an R7RS extension), then the
 360<expression> is evaluated. Its value must be a procedure that accepts
 361one argument; this procedure is then called on the value of the <key>
 362and the value(s) returned by this procedure is(are) returned by the
 363case expression.  If the result of evaluating <key> is different from
 364every <datum>, then if there is an else clause its expressions are
 365evaluated and the result(s) of the last is(are) the result(s) of the
 366case expression; otherwise the result of the case expression is
 367unspecified.
 368
 369 (case (* 2 3)
 370   ((2 3 5 7) 'prime)
 371   ((1 4 6 8 9) 'composite))             ===>  composite
 372 (case (car '(c d))
 373   ((a) 'a)
 374   ((b) 'b))                             ===>  unspecified
 375 (case (car '(c d))
 376   ((a e i o u) 'vowel)
 377   ((w y) 'semivowel)
 378   (else 'consonant))                    ===>  consonant
 379
 380<macro>(and <test[1]> ...)</macro><br>
 381
 382The <test> expressions are evaluated from left to right, and the value
 383of the first expression that evaluates to a false value (see
 384[[#Booleans|the section about booleans]]) is returned. Any remaining
 385expressions are not evaluated. If all the expressions evaluate to true
 386values, the value of the last expression is returned. If there are no
 387expressions then #t is returned.
 388
 389 (and (= 2 2) (> 2 1))                   ===>  #t
 390 (and (= 2 2) (< 2 1))                   ===>  #f
 391 (and 1 2 'c '(f g))                     ===>  (f g)
 392 (and)                                   ===>  #t
 393
 394<macro>(or <test[1]> ...)</macro><br>
 395
 396The <test> expressions are evaluated from left to right, and the value
 397of the first expression that evaluates to a true value (see
 398[[#Booleans|the section about booleans]]) is returned. Any remaining
 399expressions are not evaluated. If all expressions evaluate to false
 400values, the value of the last expression is returned. If there are no
 401expressions then #f is returned.
 402
 403 (or (= 2 2) (> 2 1))                    ===>  #t
 404 (or (= 2 2) (< 2 1))                    ===>  #t
 405 (or #f #f #f)         ===>  #f
 406 (or (memq 'b '(a b c)) 
 407     (/ 3 0))                            ===>  (b c)
 408
 409==== Binding constructs
 410
 411The three binding constructs let, let*, and letrec give Scheme a block
 412structure, like Algol 60. The syntax of the three constructs is
 413identical, but they differ in the regions they establish for their
 414variable bindings. In a let expression, the initial values are computed
 415before any of the variables become bound; in a let* expression, the
 416bindings and evaluations are performed sequentially; while in a letrec
 417expression, all the bindings are in effect while their initial values
 418are being computed, thus allowing mutually recursive definitions.
 419
 420<macro>(let <bindings> <body>)</macro><br>
 421
 422Syntax: <Bindings> should have the form
 423
 424 ((<variable[1]> <init[1]>) ...),
 425
 426where each <init> is an expression, and <body> should be a sequence of
 427one or more expressions. It is an error for a <variable> to appear more
 428than once in the list of variables being bound.
 429
 430Semantics: The <init>s are evaluated in the current environment (in
 431some unspecified order), the <variable>s are bound to fresh locations
 432holding the results, the <body> is evaluated in the extended
 433environment, and the value(s) of the last expression of <body> is(are)
 434returned. Each binding of a <variable> has <body> as its region.
 435
 436 (let ((x 2) (y 3))
 437   (* x y))                              ===>  6
 438 
 439 (let ((x 2) (y 3))
 440   (let ((x 7)
 441         (z (+ x y)))
 442     (* z x)))                           ===>  35
 443
 444See also "named let", [[#Iteration|below]].
 445
 446<macro>(let* <bindings> <body>)</macro><br>
 447
 448Syntax: <Bindings> should have the form
 449
 450 ((<variable[1]> <init[1]>) ...),
 451
 452and <body> should be a sequence of one or more expressions.
 453
 454Semantics: Let* is similar to let, but the bindings are performed
 455sequentially from left to right, and the region of a binding indicated
 456by (<variable> <init>) is that part of the let* expression to the right
 457of the binding. Thus the second binding is done in an environment in
 458which the first binding is visible, and so on.
 459
 460 (let ((x 2) (y 3))
 461   (let* ((x 7)
 462          (z (+ x y)))
 463     (* z x)))                     ===>  70
 464
 465<macro>(letrec <bindings> <body>)</macro><br>
 466
 467Syntax: <Bindings> should have the form
 468
 469 ((<variable[1]> <init[1]>) ...),
 470
 471and <body> should be a sequence of one or more expressions. It is an
 472error for a <variable> to appear more than once in the list of
 473variables being bound.
 474
 475Semantics: The <variable>s are bound to fresh locations holding
 476undefined values, the <init>s are evaluated in the resulting
 477environment (in some unspecified order), each <variable> is assigned to
 478the result of the corresponding <init>, the <body> is evaluated in the
 479resulting environment, and the value(s) of the last expression in
 480<body> is(are) returned. Each binding of a <variable> has the entire
 481letrec expression as its region, making it possible to define mutually
 482recursive procedures.
 483
 484 (letrec ((even?
 485           (lambda (n)
 486             (if (zero? n)
 487                 #t
 488                 (odd? (- n 1)))))
 489          (odd?
 490           (lambda (n)
 491             (if (zero? n)
 492                 #f
 493                 (even? (- n 1))))))
 494   (even? 88))
 495                         ===>  #t
 496
 497One restriction on letrec is very important: it must be possible to
 498evaluate each <init> without assigning or referring to the value of any
 499<variable>. If this restriction is violated, then it is an error. The
 500restriction is necessary because Scheme passes arguments by value
 501rather than by name. In the most common uses of letrec, all the <init>s
 502are lambda expressions and the restriction is satisfied automatically.
 503
 504==== Sequencing
 505
 506<macro>(begin <expression[1]> <expression[2]> ...)</macro><br>
 507
 508The <expression>s are evaluated sequentially from left to right, and
 509the value(s) of the last <expression> is(are) returned. This expression
 510type is used to sequence side effects such as input and output.
 511
 512 (define x 0)
 513 
 514 (begin (set! x 5)
 515        (+ x 1))                          ===>  6
 516 
 517 (begin (display "4 plus 1 equals ")
 518        (display (+ 4 1)))                ===>  unspecified
 519   and prints  4 plus 1 equals 5
 520
 521As an extension to R5RS, CHICKEN also allows {{(begin)}} without body
 522expressions in any context, not just at toplevel.  This simply
 523evaluates to the unspecified value.
 524
 525
 526==== Iteration
 527
 528<macro>(do ((<variable[1]> <init[1]> <step[1]>) ...) (<test> <expression> ...) <command> ...)</macro><br>
 529
 530Do is an iteration construct. It specifies a set of variables to be
 531bound, how they are to be initialized at the start, and how they are to
 532be updated on each iteration. When a termination condition is met, the
 533loop exits after evaluating the <expression>s.
 534
 535Do expressions are evaluated as follows: The <init> expressions are
 536evaluated (in some unspecified order), the <variable>s are bound to
 537fresh locations, the results of the <init> expressions are stored in
 538the bindings of the <variable>s, and then the iteration phase begins.
 539
 540Each iteration begins by evaluating <test>; if the result is false
 541(see [[#Booleans|the section about booleans]]), then the <command>
 542expressions are evaluated in order for effect, the <step> expressions
 543are evaluated in some unspecified order, the <variable>s are bound to
 544fresh locations, the results of the <step>s are stored in the bindings
 545of the <variable>s, and the next iteration begins.
 546
 547If <test> evaluates to a true value, then the <expression>s are
 548evaluated from left to right and the value(s) of the last <expression>
 549is(are) returned. If no <expression>s are present, then the value of
 550the do expression is unspecified.
 551
 552The region of the binding of a <variable> consists of the entire do
 553expression except for the <init>s. It is an error for a <variable> to
 554appear more than once in the list of do variables.
 555
 556A <step> may be omitted, in which case the effect is the same as if
 557(<variable> <init> <variable>) had been written instead of (<variable>
 558<init>).
 559
 560 (do ((vec (make-vector 5))
 561      (i 0 (+ i 1)))
 562     ((= i 5) vec)
 563   (vector-set! vec i i))                    ===>  #(0 1 2 3 4)
 564 
 565 (let ((x '(1 3 5 7 9)))
 566   (do ((x x (cdr x))
 567        (sum 0 (+ sum (car x))))
 568       ((null? x) sum)))                     ===>  25
 569
 570<macro>(let <variable> <bindings> <body>)</macro><br>
 571
 572"Named let" is a variant on the syntax of let which provides a more
 573general looping construct than do and may also be used to express
 574recursions. It has the same syntax and semantics as ordinary let except
 575that <variable> is bound within <body> to a procedure whose formal
 576arguments are the bound variables and whose body is <body>. Thus the
 577execution of <body> may be repeated by invoking the procedure named by
 578<variable>.
 579
 580 (let loop ((numbers '(3 -2 1 6 -5))
 581            (nonneg '())
 582            (neg '()))
 583   (cond ((null? numbers) (list nonneg neg))
 584         ((>= (car numbers) 0)
 585          (loop (cdr numbers)
 586                (cons (car numbers) nonneg)
 587                neg))
 588         ((< (car numbers) 0)
 589          (loop (cdr numbers)
 590                nonneg
 591                (cons (car numbers) neg)))))
 592                 ===>  ((6 1 3) (-5 -2))
 593
 594==== Delayed evaluation
 595
 596<macro>(delay <expression>)</macro><br>
 597
 598The delay construct is used together with the procedure force to
 599implement lazy evaluation or call by need. {{(delay <expression>)}}
 600returns an object called a promise which at some point in the future
 601may be asked (by the force procedure) to evaluate {{<expression>}},
 602and deliver the resulting value. The {{<expression>}} may return
 603multiple values, which will be correctly memoized and returned by
 604subsequent calls to {{force}}.  This is a CHICKEN extension to R5RS.
 605
 606See the description of {{force}} (under [[#control-features|Control
 607features]], below) for a more complete description of {{delay}}.
 608
 609CHICKEN also supports the R7RS {{delay-force}} syntax which allows for
 610iterative lazy algorithms to be expressed in bounded space.  See the
 611[[Module (chicken base)#lazy-evaluation|Lazy evaluation section]] in
 612the (chicken base) module documentation for more information.
 613
 614
 615==== Quasiquotation
 616
 617<macro>(quasiquote <qq template>)</macro><br>
 618<macro>`<qq template></macro><br>
 619
 620"Backquote" or "quasiquote" expressions are useful for constructing
 621a list or vector structure when most but not all of the desired
 622structure is known in advance. If no commas appear within the <qq
 623template>, the result of evaluating `<qq template> is equivalent to the
 624result of evaluating '<qq template>. If a comma appears within the <qq
 625template>, however, the expression following the comma is evaluated
 626("unquoted") and its result is inserted into the structure instead of
 627the comma and the expression. If a comma appears followed immediately
 628by an at-sign (@), then the following expression must evaluate to a
 629list; the opening and closing parentheses of the list are then
 630"stripped away" and the elements of the list are inserted in place of
 631the comma at-sign expression sequence. A comma at-sign should only
 632appear within a list or vector <qq template>.
 633
 634 `(list ,(+ 1 2) 4)          ===>  (list 3 4)
 635 (let ((name 'a)) `(list ,name ',name))           
 636                 ===>  (list a (quote a))
 637 `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b)           
 638                 ===>  (a 3 4 5 6 b)
 639 `(( foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))           
 640                 ===>  ((foo 7) . cons)
 641 `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)           
 642                 ===>  #(10 5 2 4 3 8)
 643
 644Quasiquote forms may be nested. Substitutions are made only for
 645unquoted components appearing at the same nesting level as the
 646outermost backquote. The nesting level increases by one inside each
 647successive quasiquotation, and decreases by one inside each
 648unquotation.
 649
 650 `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)           
 651                 ===>  (a `(b ,(+ 1 2) ,(foo 4 d) e) f)
 652 (let ((name1 'x)
 653       (name2 'y))
 654   `(a `(b ,,name1 ,',name2 d) e))           
 655                 ===>  (a `(b ,x ,'y d) e)
 656
 657The two notations `<qq template> and (quasiquote <qq template>) are
 658identical in all respects. ,<expression> is identical to (unquote
 659<expression>), and ,@<expression> is identical to (unquote-splicing
 660<expression>). The external syntax generated by write for two-element
 661lists whose car is one of these symbols may vary between
 662implementations.
 663
 664 (quasiquote (list (unquote (+ 1 2)) 4))           
 665                 ===>  (list 3 4)
 666 '(quasiquote (list (unquote (+ 1 2)) 4))           
 667                 ===>  `(list ,(+ 1 2) 4)
 668      i.e., (quasiquote (list (unquote (+ 1 2)) 4))
 669
 670Unpredictable behavior can result if any of the symbols quasiquote,
 671unquote, or unquote-splicing appear in positions within a <qq template>
 672otherwise than as described above.
 673
 674=== Macros
 675
 676Scheme programs can define and use new derived expression types, called
 677macros. Program-defined expression types have the syntax
 678
 679 (<keyword> <datum> ...)
 680
 681where <keyword> is an identifier that uniquely determines the
 682expression type. This identifier is called the syntactic keyword, or
 683simply keyword, of the macro. The number of the <datum>s, and their
 684syntax, depends on the expression type.
 685
 686Each instance of a macro is called a use of the macro. The set of rules
 687that specifies how a use of a macro is transcribed into a more
 688primitive expression is called the transformer of the macro.
 689
 690The macro definition facility consists of two parts:
 691
 692*   A set of expressions used to establish that certain identifiers are
 693    macro keywords, associate them with macro transformers, and control
 694    the scope within which a macro is defined, and
 695
 696*   a pattern language for specifying macro transformers.
 697
 698The syntactic keyword of a macro may shadow variable bindings, and
 699local variable bindings may shadow keyword bindings. All macros defined
 700using the pattern language are "hygienic" and "referentially
 701transparent" and thus preserve Scheme's lexical scoping:
 702
 703*   If a macro transformer inserts a binding for an identifier
 704    (variable or keyword), the identifier will in effect be renamed
 705    throughout its scope to avoid conflicts with other identifiers.
 706    Note that a define at top level may or may not introduce a binding;
 707    this depends on whether the binding already existed before (in which
 708    case its value will be overridden).
 709
 710*   If a macro transformer inserts a free reference to an identifier,
 711    the reference refers to the binding that was visible where the
 712    transformer was specified, regardless of any local bindings that
 713    may surround the use of the macro.
 714
 715==== Binding constructs for syntactic keywords
 716
 717Let-syntax and letrec-syntax are analogous to let and letrec, but they
 718bind syntactic keywords to macro transformers instead of binding
 719variables to locations that contain values. Syntactic keywords may also
 720be bound at top level.
 721
 722<macro>(let-syntax <bindings> <body>)</macro><br>
 723
 724Syntax: <Bindings> should have the form
 725
 726 ((<keyword> <transformer spec>) ...)
 727
 728Each <keyword> is an identifier, each <transformer spec> is an instance
 729of syntax-rules, and <body> should be a sequence of one or more
 730expressions. It is an error for a <keyword> to appear more than once in
 731the list of keywords being bound.
 732
 733Semantics: The <body> is expanded in the syntactic environment obtained
 734by extending the syntactic environment of the let-syntax expression
 735with macros whose keywords are the <keyword>s, bound to the specified
 736transformers. Each binding of a <keyword> has <body> as its region.
 737
 738 (let-syntax ((when (syntax-rules ()
 739                      ((when test stmt1 stmt2 ...)
 740                       (if test
 741                           (begin stmt1
 742                                  stmt2 ...))))))
 743   (let ((if #t))
 744     (when if (set! if 'now))
 745     if))                                   ===>  now
 746 
 747 (let ((x 'outer))
 748   (let-syntax ((m (syntax-rules () ((m) x))))
 749     (let ((x 'inner))
 750       (m))))                               ===>  outer
 751
 752<macro>(letrec-syntax <bindings> <body>)</macro><br>
 753
 754Syntax: Same as for let-syntax.
 755
 756Semantics: The <body> is expanded in the syntactic environment obtained
 757by extending the syntactic environment of the letrec-syntax expression
 758with macros whose keywords are the <keyword>s, bound to the specified
 759transformers. Each binding of a <keyword> has the <bindings> as well as
 760the <body> within its region, so the transformers can transcribe
 761expressions into uses of the macros introduced by the letrec-syntax
 762expression.
 763
 764 (letrec-syntax
 765   ((my-or (syntax-rules ()
 766             ((my-or) #f)
 767             ((my-or e) e)
 768             ((my-or e1 e2 ...)
 769              (let ((temp e1))
 770                (if temp
 771                    temp
 772                    (my-or e2 ...)))))))
 773   (let ((x #f)
 774         (y 7)
 775         (temp 8)
 776         (let odd?)
 777         (if even?))
 778     (my-or x
 779            (let temp)
 780            (if y)
 781            y)))                ===>  7
 782
 783==== Pattern language
 784
 785A <transformer spec> has the following form:
 786
 787 (syntax-rules <literals> <syntax rule> ...)
 788
 789Syntax: <Literals> is a list of identifiers and each <syntax rule>
 790should be of the form
 791
 792 (<pattern> <template>)
 793
 794The <pattern> in a <syntax rule> is a list <pattern> that begins with
 795the keyword for the macro.
 796
 797A <pattern> is either an identifier, a constant, or one of the
 798following
 799
 800 (<pattern> ...)
 801 (<pattern> <pattern> ... . <pattern>)
 802 (<pattern> ... <pattern> <ellipsis>)
 803 #(<pattern> ...)
 804 #(<pattern> ... <pattern> <ellipsis>)
 805
 806and a template is either an identifier, a constant, or one of the
 807following
 808
 809 (<element> ...)
 810 (<element> <element> ... . <template>)
 811 #(<element> ...)
 812
 813where an <element> is a <template> optionally followed by an <ellipsis>
 814and an <ellipsis> is the identifier "..." (which cannot be used as an
 815identifier in either a template or a pattern).
 816
 817Semantics: An instance of syntax-rules produces a new macro transformer
 818by specifying a sequence of hygienic rewrite rules. A use of a macro
 819whose keyword is associated with a transformer specified by
 820syntax-rules is matched against the patterns contained in the <syntax
 821rule>s, beginning with the leftmost <syntax rule>. When a match is
 822found, the macro use is transcribed hygienically according to the
 823template.
 824
 825An identifier that appears in the pattern of a <syntax rule> is a
 826pattern variable, unless it is the keyword that begins the pattern, is
 827listed in <literals>, or is the identifier "...". Pattern variables
 828match arbitrary input elements and are used to refer to elements of the
 829input in the template. It is an error for the same pattern variable to
 830appear more than once in a <pattern>.
 831
 832The keyword at the beginning of the pattern in a <syntax rule> is not
 833involved in the matching and is not considered a pattern variable or
 834literal identifier.
 835
 836Rationale:   The scope of the keyword is determined by the
 837expression or syntax definition that binds it to the associated
 838macro transformer. If the keyword were a pattern variable or
 839literal identifier, then the template that follows the pattern
 840would be within its scope regardless of whether the keyword were
 841bound by let-syntax or by letrec-syntax.
 842
 843Identifiers that appear in <literals> are interpreted as literal
 844identifiers to be matched against corresponding subforms of the input.
 845A subform in the input matches a literal identifier if and only if it
 846is an identifier and either both its occurrence in the macro expression
 847and its occurrence in the macro definition have the same lexical
 848binding, or the two identifiers are equal and both have no lexical
 849binding.
 850
 851A subpattern followed by ... can match zero or more elements of the
 852input. It is an error for ... to appear in <literals>. Within a pattern
 853the identifier ... must follow the last element of a nonempty sequence
 854of subpatterns.
 855
 856More formally, an input form F matches a pattern P if and only if:
 857
 858*   P is a non-literal identifier; or
 859
 860*   P is a literal identifier and F is an identifier with the same
 861    binding; or
 862
 863*   P is a list (P[1] ... P[n]) and F is a list of n forms that match P
 864    [1] through P[n], respectively; or
 865
 866*   P is an improper list (P[1] P[2] ... P[n] . P[n+1]) and F is a list
 867    or improper list of n or more forms that match P[1] through P[n],
 868    respectively, and whose nth "cdr" matches P[n+1]; or
 869
 870*   P is of the form (P[1] ... P[n] P[n+1] <ellipsis>) where <ellipsis>
 871    is the identifier ... and F is a proper list of at least n forms,
 872    the first n of which match P[1] through P[n], respectively, and
 873    each remaining element of F matches P[n+1]; or
 874
 875*   P is a vector of the form #(P[1] ... P[n]) and F is a vector of n
 876    forms that match P[1] through P[n]; or
 877
 878*   P is of the form #(P[1] ... P[n] P[n+1] <ellipsis>) where
 879    <ellipsis> is the identifier ... and F is a vector of n or more
 880    forms the first n of which match P[1] through P[n], respectively,
 881    and each remaining element of F matches P[n+1]; or
 882
 883*   P is a datum and F is equal to P in the sense of the equal?
 884    procedure.
 885
 886It is an error to use a macro keyword, within the scope of its binding,
 887in an expression that does not match any of the patterns.
 888
 889When a macro use is transcribed according to the template of the
 890matching <syntax rule>, pattern variables that occur in the template
 891are replaced by the subforms they match in the input. Pattern variables
 892that occur in subpatterns followed by one or more instances of the
 893identifier ... are allowed only in subtemplates that are followed by as
 894many instances of .... They are replaced in the output by all of the
 895subforms they match in the input, distributed as indicated. It is an
 896error if the output cannot be built up as specified.
 897
 898Identifiers that appear in the template but are not pattern variables
 899or the identifier ... are inserted into the output as literal
 900identifiers. If a literal identifier is inserted as a free identifier
 901then it refers to the binding of that identifier within whose scope the
 902instance of syntax-rules appears. If a literal identifier is inserted
 903as a bound identifier then it is in effect renamed to prevent
 904inadvertent captures of free identifiers.
 905
 906As an example, if let and cond are defined as usual, then they are
 907hygienic (as required) and the following is not an error.
 908
 909 (let ((=> #f))
 910   (cond (#t => 'ok)))                   ===> ok
 911
 912The macro transformer for cond recognizes => as a local variable, and
 913hence an expression, and not as the top-level identifier =>, which the
 914macro transformer treats as a syntactic keyword. Thus the example
 915expands into
 916
 917 (let ((=> #f))
 918   (if #t (begin => 'ok)))
 919
 920instead of
 921
 922 (let ((=> #f))
 923   (let ((temp #t))
 924     (if temp ('ok temp))))
 925
 926which would result in an invalid procedure call.
 927
 928== Program structure
 929
 930=== Programs
 931
 932A Scheme program consists of a sequence of expressions, definitions,
 933and syntax definitions. Expressions are described in chapter 4;
 934definitions and syntax definitions are the subject of the rest of the
 935present chapter.
 936
 937Programs are typically stored in files or entered interactively to a
 938running Scheme system, although other paradigms are possible;
 939questions of user interface lie outside the scope of this
 940report. (Indeed, Scheme would still be useful as a notation for
 941expressing computational methods even in the absence of a mechanical
 942implementation.)
 943
 944Definitions and syntax definitions occurring at the top level of a
 945program can be interpreted declaratively. They cause bindings to be
 946created in the top level environment or modify the value of existing
 947top-level bindings. Expressions occurring at the top level of a
 948program are interpreted imperatively; they are executed in order when
 949the program is invoked or loaded, and typically perform some kind of
 950initialization.
 951
 952At the top level of a program (begin <form1> ...) is equivalent to the
 953sequence of expressions, definitions, and syntax definitions that form
 954the body of the begin.
 955
 956=== Definitions
 957
 958Definitions are valid in some, but not all, contexts where expressions
 959are allowed. They are valid only at the top level of a <program> and
 960at the beginning of a <body>.
 961
 962A definition should have one of the following forms:
 963
 964<macro>(define <variable> <expression>)</macro><br>
 965<macro>(define (<variable> <formals>) <body>)</macro><br>
 966
 967<Formals> should be either a sequence of zero or more variables, or a
 968sequence of one or more variables followed by a space-delimited period
 969and another variable (as in a lambda expression). This form is
 970equivalent to
 971
 972 (define <variable>
 973   (lambda (<formals>) <body>)).
 974
 975<macro>(define <variable>)</macro>
 976
 977This form is a CHICKEN extension to R5RS, and is equivalent to
 978
 979 (define <variable> (void))
 980
 981<macro>(define (<variable> . <formal>) <body>)</macro><br>
 982
 983<Formal> should be a single variable. This form is equivalent to
 984
 985 (define <variable>
 986   (lambda <formal> <body>)).
 987
 988<macro>(define ((<variable> <formal> ...) ...) <body>)</macro><br>
 989
 990As an extension to R5RS, CHICKEN allows ''curried'' definitions, where
 991the variable name may also be a list specifying a name and a nested
 992lambda list. For example,
 993
 994 (define ((make-adder x) y) (+ x y))
 995
 996is equivalent to
 997
 998 (define (make-adder x) (lambda (y) (+ x y))).
 999
 1000This type of curried definition can be nested arbitrarily and combined
1001with dotted tail notation or DSSSL keywords.
1002
1003==== Top level definitions
1004
1005At the top level of a program, a definition
1006
1007 (define <variable> <expression>)
1008
1009has essentially the same effect as the assignment expression
1010
1011 (set! <variable> <expression>)
1012
1013if <variable> is bound. If <variable> is not bound, however, then the
1014definition will bind <variable> to a new location before performing
1015the assignment, whereas it would be an error to perform a set! on an
1016unbound variable in standard Scheme.  In CHICKEN, {{set!}} at toplevel
1017has the same effect as a definition, unless inside a module, in which
1018case it is an error.
1019
1020 (define add3
1021   (lambda (x) (+ x 3)))
1022 (add3 3)                         ===>  6
1023 (define first car)
1024 (first '(1 2))                   ===>  1
1025
1026Some implementations of Scheme use an initial environment in which all
1027possible variables are bound to locations, most of which contain
1028undefined values. Top level definitions in such an implementation are
1029truly equivalent to assignments.  In CHICKEN, attempting to evaluate
1030an unbound identifier will result in an error, but you ''can'' use
1031{{set!}} to bind an initial value to it.
1032
1033==== Internal definitions
1034
1035Definitions may occur at the beginning of a <body> (that is, the body
1036of a lambda, let, let*, letrec, let-syntax, or letrec-syntax
1037expression or that of a definition of an appropriate form). Such
1038definitions are known as internal definitions as opposed to the top
1039level definitions described above. The variable defined by an internal
1040definition is local to the <body>. That is, <variable> is bound rather
1041than assigned, and the region of the binding is the entire <body>. For
1042example,
1043
1044 (let ((x 5))
1045   (define foo (lambda (y) (bar x y)))
1046   (define bar (lambda (a b) (+ (* a b) a)))
1047   (foo (+ x 3)))                        ===>  45
1048
1049A <body> containing internal definitions can always be converted into
1050a completely equivalent letrec expression. For example, the let
1051expression in the above example is equivalent to
1052
1053 (let ((x 5))
1054   (letrec ((foo (lambda (y) (bar x y)))
1055            (bar (lambda (a b) (+ (* a b) a))))
1056     (foo (+ x 3))))
1057
1058Just as for the equivalent letrec expression, it must be possible to
1059evaluate each <expression> of every internal definition in a <body>
1060without assigning or referring to the value of any <variable> being
1061defined.
1062
1063Wherever an internal definition may occur (begin <definition1> ...) is
1064equivalent to the sequence of definitions that form the body of the
1065begin.
1066
1067CHICKEN extends the R5RS semantics by allowing internal definitions
1068everywhere, and not only at the beginning of a body. A set of internal
1069definitions is equivalent to a {{letrec}} form enclosing all following
1070expressions in the body:
1071
1072 (let ((foo 123))
1073   (bar)
1074   (define foo 456)
1075   (baz foo) )
1076
1077expands into
1078
1079 (let ((foo 123))
1080   (bar)
1081   (letrec ((foo 456))
1082     (baz foo) ) )
1083
1084Local sequences of {{define-syntax}} forms are translated into
1085equivalent {{letrec-syntax}} forms that enclose the following forms as
1086the body of the expression.
1087
1088
1089=== Syntax definitions
1090
1091Syntax definitions are valid only at the top level of a
1092<program>. They have the following form:
1093
1094<macro>(define-syntax <keyword> <transformer spec>)</macro>
1095
1096{{<Keyword>}} is an identifier, and the {{<transformer spec>}} should
1097be an instance of {{syntax-rules}}.  Note that CHICKEN also supports
1098{{er-macro-transformer}} and {{ir-macro-transformer}} here.  For more
1099information see [[Module (chicken syntax)|the (chicken syntax) module]].
1100
1101The top-level syntactic environment is extended by binding the
1102<keyword> to the specified transformer.
1103
1104In standard Scheme, there is no define-syntax analogue of internal
1105definitions in, but CHICKEN allows these as an extension to the
1106standard.  This means {{define-syntax}} may be used to define local
1107macros that are visible throughout the rest of the body in which the
1108definition occurred, i.e.
1109
1110  (let ()
1111    ...
1112    (define-syntax foo ...)
1113    (define-syntax bar ...)
1114    ...)
1115
1116is expanded into
1117
1118  (let ()
1119    ...
1120    (letrec-syntax ((foo ...) (bar ...))
1121      ...) )
1122
1123{{syntax-rules}} supports [[http://srfi.schemers.org/srfi-46/|SRFI-46]]
1124in allowing the ellipsis identifier to be user-defined by passing it as the first
1125argument to the {{syntax-rules}} form. Also, "tail" patterns of the form
1126
1127  (syntax-rules ()
1128    ((_ (a b ... c) 
1129      ...
1130
1131are supported.
1132
1133The effect of destructively modifying the s-expression passed to a
1134transformer procedure is undefined.
1135
1136Although macros may expand into definitions and syntax definitions in
1137any context that permits them, it is an error for a definition or
1138syntax definition to shadow a syntactic keyword whose meaning is
1139needed to determine whether some form in the group of forms that
1140contains the shadowing definition is in fact a definition, or, for
1141internal definitions, is needed to determine the boundary between the
1142group and the expressions that follow the group. For example, the
1143following are errors:
1144
1145 (define define 3)
1146
1147 (begin (define begin list))
1148
1149 (let-syntax
1150   ((foo (syntax-rules ()
1151           ((foo (proc args ...) body ...)
1152            (define proc
1153              (lambda (args ...)
1154                body ...))))))
1155   (let ((x 3))
1156     (foo (plus x y) (+ x y))
1157     (define foo x)
1158     (plus foo x)))
1159
1160== Standard procedures
1161
1162This chapter describes Scheme's built-in procedures. The initial (or
1163"top level") Scheme environment starts out with a number of variables
1164bound to locations containing useful values, most of which are
1165primitive procedures that manipulate data. For example, the variable
1166abs is bound to (a location initially containing) a procedure of one
1167argument that computes the absolute value of a number, and the variable
1168+ is bound to a procedure that computes sums. Built-in procedures that
1169can easily be written in terms of other built-in procedures are
1170identified as "library procedures".
1171
1172A program may use a top-level definition to bind any variable. It may
1173subsequently alter any such binding by an assignment (see
1174[[#assignments|assignments]], above). These operations do
1175not modify the behavior of Scheme's built-in procedures. Altering any
1176top-level binding that has not been introduced by a definition has an
1177unspecified effect on the behavior of the built-in procedures.
1178
1179=== Equivalence predicates
1180
1181A predicate is a procedure that always returns a boolean value (#t or #f).
1182An equivalence predicate is the computational analogue of a
1183mathematical equivalence relation (it is symmetric, reflexive, and
1184transitive). Of the equivalence predicates described in this section,
1185eq? is the finest or most discriminating, and equal? is the coarsest.
1186eqv? is slightly less discriminating than eq?.
1187
1188<procedure>(eqv? obj[1] obj[2])</procedure><br>
1189
1190The eqv? procedure defines a useful equivalence relation on objects.
1191Briefly, it returns #t if obj[1] and obj[2] should normally be regarded
1192as the same object. This relation is left slightly open to
1193interpretation, but the following partial specification of eqv? holds
1194for all implementations of Scheme.
1195
1196The eqv? procedure returns #t if:
1197
1198*   obj[1] and obj[2] are both #t or both #f.
1199
1200*   obj[1] and obj[2] are both symbols and
1201
1202    (string=? (symbol->string obj1)
1203              (symbol->string obj2))
1204                ===>  #t
1205
1206Note: This assumes that neither obj[1] nor obj[2] is an "uninterned
1207symbol" as alluded to in the section on [[#symbols|symbols]]. This
1208report does not presume to specify the behavior of eqv? on
1209implementation-dependent extensions.
1210
1211*   obj[1] and obj[2] are both numbers, are numerically equal (see =,
1212    under [[#numerical-operations|numerical operations]]), and are
1213    either both exact or both inexact.
1214
1215*   obj[1] and obj[2] are both characters and are the same character
1216    according to the char=? procedure (see "[[#characters|characters]]").
1217
1218*   both obj[1] and obj[2] are the empty list.
1219
1220*   obj[1] and obj[2] are pairs, vectors, or strings that denote the
1221    same locations in the store.
1222
1223*   obj[1] and obj[2] are procedures whose location tags are equal
1224    (see "[[#procedures|procedures]]").
1225
1226The eqv? procedure returns #f if:
1227
1228*   obj[1] and obj[2] are of different types.
1229
1230*   one of obj[1] and obj[2] is #t but the other is #f.
1231
1232*   obj[1] and obj[2] are symbols but
1233
1234    (string=? (symbol->string obj[1])
1235              (symbol->string obj[2]))
1236                ===>  #f
1237
1238*   one of obj[1] and obj[2] is an exact number but the other is an
1239    inexact number.
1240
1241*   obj[1] and obj[2] are numbers for which the = procedure returns #f.
1242
1243*   obj[1] and obj[2] are characters for which the char=? procedure
1244    returns #f.
1245
1246*   one of obj[1] and obj[2] is the empty list but the other is not.
1247
1248*   obj[1] and obj[2] are pairs, vectors, or strings that denote
1249    distinct locations.
1250
1251*   obj[1] and obj[2] are procedures that would behave differently
1252    (return different value(s) or have different side effects) for some
1253    arguments.
1254
1255 (eqv? 'a 'a)                             ===>  #t
1256 (eqv? 'a 'b)                             ===>  #f
1257 (eqv? 2 2)                               ===>  #t
1258 (eqv? '() '())                           ===>  #t
1259 (eqv? 100000000 100000000)               ===>  #t
1260 (eqv? (cons 1 2) (cons 1 2))             ===>  #f
1261 (eqv? (lambda () 1)
1262       (lambda () 2))                     ===>  #f
1263 (eqv? #f 'nil)                           ===>  #f
1264 (let ((p (lambda (x) x)))
1265   (eqv? p p))                            ===>  #t
1266
1267The following examples illustrate cases in which the above rules do not
1268fully specify the behavior of eqv?. All that can be said about such
1269cases is that the value returned by eqv? must be a boolean.
1270
1271 (eqv? "" "")                     ===>  unspecified
1272 (eqv? '#() '#())                 ===>  unspecified
1273 (eqv? (lambda (x) x)
1274       (lambda (x) x))            ===>  unspecified
1275 (eqv? (lambda (x) x)
1276       (lambda (y) y))            ===>  unspecified
1277
1278The next set of examples shows the use of eqv? with procedures that
1279have local state. Gen-counter must return a distinct procedure every
1280time, since each procedure has its own internal counter. Gen-loser,
1281however, returns equivalent procedures each time, since the local state
1282does not affect the value or side effects of the procedures.
1283
1284 (define gen-counter
1285   (lambda ()
1286     (let ((n 0))
1287       (lambda () (set! n (+ n 1)) n))))
1288 (let ((g (gen-counter)))
1289   (eqv? g g))                   ===>  #t
1290 (eqv? (gen-counter) (gen-counter))
1291                                 ===>  #f
1292 (define gen-loser
1293   (lambda ()
1294     (let ((n 0))
1295       (lambda () (set! n (+ n 1)) 27))))
1296 (let ((g (gen-loser)))
1297   (eqv? g g))                   ===>  #t
1298 (eqv? (gen-loser) (gen-loser))
1299                                 ===>  unspecified
1300 
1301 (letrec ((f (lambda () (if (eqv? f g) 'both 'f)))
1302          (g (lambda () (if (eqv? f g) 'both 'g))))
1303   (eqv? f g))
1304                                 ===>  unspecified
1305 
1306 (letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
1307          (g (lambda () (if (eqv? f g) 'g 'both))))
1308   (eqv? f g))
1309                                 ===>  #f
1310
1311Since it is an error to modify constant objects (those returned by
1312literal expressions), implementations are permitted, though not
1313required, to share structure between constants where appropriate. Thus
1314the value of eqv? on constants is sometimes implementation-dependent.
1315
1316 (eqv? '(a) '(a))                         ===>  unspecified
1317 (eqv? "a" "a")                           ===>  unspecified
1318 (eqv? '(b) (cdr '(a b)))                 ===>  unspecified
1319 (let ((x '(a)))
1320   (eqv? x x))                            ===>  #t
1321
1322Rationale:   The above definition of eqv? allows implementations
1323latitude in their treatment of procedures and literals:
1324implementations are free either to detect or to fail to detect that
1325two procedures or two literals are equivalent to each other, and
1326can decide whether or not to merge representations of equivalent
1327objects by using the same pointer or bit pattern to represent both.
1328
1329<procedure>(eq? obj[1] obj[2])</procedure><br>
1330
1331Eq? is similar to eqv? except that in some cases it is capable of
1332discerning distinctions finer than those detectable by eqv?.
1333
1334Eq? and eqv? are guaranteed to have the same behavior on symbols,
1335booleans, the empty list, pairs, procedures, and non-empty strings and
1336vectors. Eq?'s behavior on numbers and characters is
1337implementation-dependent, but it will always return either true or
1338false, and will return true only when eqv? would also return true. Eq?
1339may also behave differently from eqv? on empty vectors and empty
1340strings.
1341
1342 (eq? 'a 'a)                             ===>  #t
1343 (eq? '(a) '(a))                         ===>  unspecified
1344 (eq? (list 'a) (list 'a))               ===>  #f
1345 (eq? "a" "a")                           ===>  unspecified
1346 (eq? "" "")                             ===>  unspecified
1347 (eq? '() '())                           ===>  #t
1348 (eq? 2 2)                               ===>  unspecified
1349 (eq? #\A #\A)                           ===>  unspecified
1350 (eq? car car)                           ===>  #t
1351 (let ((n (+ 2 3)))
1352   (eq? n n))              ===>  unspecified
1353 (let ((x '(a)))
1354   (eq? x x))              ===>  #t
1355 (let ((x '#()))
1356   (eq? x x))              ===>  #t
1357 (let ((p (lambda (x) x)))
1358   (eq? p p))              ===>  #t
1359
1360Rationale:   It will usually be possible to implement eq? much more
1361efficiently than eqv?, for example, as a simple pointer comparison
1362instead of as some more complicated operation. One reason is that
1363it may not be possible to compute eqv? of two numbers in constant
1364time, whereas eq? implemented as pointer comparison will always
1365finish in constant time. Eq? may be used like eqv? in applications
1366using procedures to implement objects with state since it obeys the
1367same constraints as eqv?.
1368
1369<procedure>(equal? obj[1] obj[2])</procedure><br>
1370
1371Equal? recursively compares the contents of pairs, vectors, and
1372strings, applying eqv? on other objects such as numbers and symbols. A
1373rule of thumb is that objects are generally equal? if they print the
1374same. Equal? may fail to terminate if its arguments are circular data
1375structures.
1376
1377 (equal? 'a 'a)                          ===>  #t
1378 (equal? '(a) '(a))                      ===>  #t
1379 (equal? '(a (b) c)
1380         '(a (b) c))                     ===>  #t
1381 (equal? "abc" "abc")                    ===>  #t
1382 (equal? 2 2)                            ===>  #t
1383 (equal? (make-vector 5 'a)
1384         (make-vector 5 'a))             ===>  #t
1385 (equal? (lambda (x) x)
1386         (lambda (y) y))          ===>  unspecified
1387
1388=== Numbers
1389
1390Numerical computation has traditionally been neglected by the Lisp
1391community. Until Common Lisp there was no carefully thought out
1392strategy for organizing numerical computation, and with the exception
1393of the MacLisp system [20] little effort was made to execute numerical
1394code efficiently. This report recognizes the excellent work of the
1395Common Lisp committee and accepts many of their recommendations. In
1396some ways this report simplifies and generalizes their proposals in a
1397manner consistent with the purposes of Scheme.
1398
1399It is important to distinguish between the mathematical numbers, the
1400Scheme numbers that attempt to model them, the machine representations
1401used to implement the Scheme numbers, and notations used to write
1402numbers. This report uses the types number, complex, real, rational,
1403and integer to refer to both mathematical numbers and Scheme numbers.
1404Machine representations such as fixed point and floating point are
1405referred to by names such as fixnum and flonum.
1406
1407==== Numerical types
1408
1409Mathematically, numbers may be arranged into a tower of subtypes in
1410which each level is a subset of the level above it:
1411
1412    number
1413    complex
1414    real
1415    rational
1416    integer
1417
1418For example, 3 is an integer. Therefore 3 is also a rational, a real,
1419and a complex. The same is true of the Scheme numbers that model 3. For
1420Scheme numbers, these types are defined by the predicates number?,
1421complex?, real?, rational?, and integer?.
1422
1423There is no simple relationship between a number's type and its
1424representation inside a computer. Although most implementations of
1425Scheme will offer at least two different representations of 3, these
1426different representations denote the same integer.
1427
1428Scheme's numerical operations treat numbers as abstract data, as
1429independent of their representation as possible. Although an
1430implementation of Scheme may use fixnum, flonum, and perhaps other
1431representations for numbers, this should not be apparent to a casual
1432programmer writing simple programs.
1433
1434It is necessary, however, to distinguish between numbers that are
1435represented exactly and those that may not be. For example, indexes
1436into data structures must be known exactly, as must some polynomial
1437coefficients in a symbolic algebra system. On the other hand, the
1438results of measurements are inherently inexact, and irrational numbers
1439may be approximated by rational and therefore inexact approximations.
1440In order to catch uses of inexact numbers where exact numbers are
1441required, Scheme explicitly distinguishes exact from inexact numbers.
1442This distinction is orthogonal to the dimension of type.
1443
1444==== Exactness
1445
1446Scheme numbers are either exact or inexact. A number is exact if it was
1447written as an exact constant or was derived from exact numbers using
1448only exact operations. A number is inexact if it was written as an
1449inexact constant, if it was derived using inexact ingredients, or if it
1450was derived using inexact operations. Thus inexactness is a contagious
1451property of a number. If two implementations produce exact results for
1452a computation that did not involve inexact intermediate results, the
1453two ultimate results will be mathematically equivalent. This is
1454generally not true of computations involving inexact numbers since
1455approximate methods such as floating point arithmetic may be used, but
1456it is the duty of each implementation to make the result as close as
1457practical to the mathematically ideal result.
1458
1459Rational operations such as + should always produce exact results when
1460given exact arguments. If the operation is unable to produce an exact
1461result, then it may either report the violation of an implementation
1462restriction or it may silently coerce its result to an inexact value.
1463See [[#Implementation restrictions|the next section]].
1464
1465With the exception of inexact->exact, the operations described in this
1466section must generally return inexact results when given any inexact
1467arguments. An operation may, however, return an exact result if it can
1468prove that the value of the result is unaffected by the inexactness of
1469its arguments. For example, multiplication of any number by an exact
1470zero may produce an exact zero result, even if the other argument is
1471inexact.
1472
1473==== Implementation restrictions
1474
1475Implementations of Scheme are not required to implement the whole
1476tower of subtypes given under "[[#Numerical types|Numerical types]]",
1477but they must implement a coherent subset consistent with both the
1478purposes of the implementation and the spirit of the Scheme
1479language. For example, an implementation in which all numbers are real
1480may still be quite useful.
1481
1482Implementations may also support only a limited range of numbers of any
1483type, subject to the requirements of this section. The supported range
1484for exact numbers of any type may be different from the supported range
1485for inexact numbers of that type. For example, an implementation that
1486uses flonums to represent all its inexact real numbers may support a
1487practically unbounded range of exact integers and rationals while
1488limiting the range of inexact reals (and therefore the range of inexact
1489integers and rationals) to the dynamic range of the flonum format.
1490Furthermore the gaps between the representable inexact integers and
1491rationals are likely to be very large in such an implementation as the
1492limits of this range are approached.
1493
1494An implementation of Scheme must support exact integers throughout the
1495range of numbers that may be used for indexes of lists, vectors, and
1496strings or that may result from computing the length of a list, vector,
1497or string. The length, vector-length, and string-length procedures must
1498return an exact integer, and it is an error to use anything but an
1499exact integer as an index. Furthermore any integer constant within the
1500index range, if expressed by an exact integer syntax, will indeed be
1501read as an exact integer, regardless of any implementation restrictions
1502that may apply outside this range. Finally, the procedures listed below
1503will always return an exact integer result provided all their arguments
1504are exact integers and the mathematically expected result is
1505representable as an exact integer within the implementation:
1506
1507 +            -             *
1508 quotient     remainder     modulo
1509 max          min           abs
1510 numerator    denominator   gcd
1511 lcm          floor         ceiling
1512 truncate     round         rationalize
1513 expt
1514
1515Implementations are encouraged, but not required, to support exact
1516integers and exact rationals of practically unlimited size and
1517precision, and to implement the above procedures and the / procedure in
1518such a way that they always return exact results when given exact
1519arguments. If one of these procedures is unable to deliver an exact
1520result when given exact arguments, then it may either report a
1521violation of an implementation restriction or it may silently coerce
1522its result to an inexact number. Such a coercion may cause an error
1523later.
1524
1525An implementation may use floating point and other approximate
1526representation strategies for inexact numbers. This report recommends,
1527but does not require, that the IEEE 32-bit and 64-bit floating point
1528standards be followed by implementations that use flonum
1529representations, and that implementations using other representations
1530should match or exceed the precision achievable using these floating
1531point standards [12].
1532
1533In particular, implementations that use flonum representations must
1534follow these rules: A flonum result must be represented with at least
1535as much precision as is used to express any of the inexact arguments to
1536that operation. It is desirable (but not required) for potentially
1537inexact operations such as sqrt, when applied to exact arguments, to
1538produce exact answers whenever possible (for example the square root of
1539an exact 4 ought to be an exact 2). If, however, an exact number is
1540operated upon so as to produce an inexact result (as by sqrt), and if
1541the result is represented as a flonum, then the most precise flonum
1542format available must be used; but if the result is represented in some
1543other way then the representation must have at least as much precision
1544as the most precise flonum format available.
1545
1546Although Scheme allows a variety of written notations for numbers, any
1547particular implementation may support only some of them. For example,
1548an implementation in which all numbers are real need not support the
1549rectangular and polar notations for complex numbers. If an
1550implementation encounters an exact numerical constant that it cannot
1551represent as an exact number, then it may either report a violation of
1552an implementation restriction or it may silently represent the constant
1553by an inexact number.
1554
1555==== Syntax of numerical constants
1556
1557For a complete formal description of the syntax of the written
1558representations for numbers, see the R5RS report. Note that case is
1559not significant in numerical constants.
1560
1561A number may be written in binary, octal, decimal, or hexadecimal by
1562the use of a radix prefix. The radix prefixes are #b (binary), #o
1563(octal), #d (decimal), and #x (hexadecimal). With no radix prefix, a
1564number is assumed to be expressed in decimal.
1565
1566A numerical constant may be specified to be either exact or inexact by
1567a prefix. The prefixes are #e for exact, and #i for inexact. An
1568exactness prefix may appear before or after any radix prefix that is
1569used. If the written representation of a number has no exactness
1570prefix, the constant may be either inexact or exact. It is inexact if
1571it contains a decimal point, an exponent, or a "#" character in the
1572place of a digit, otherwise it is exact. In systems with inexact
1573numbers of varying precisions it may be useful to specify the precision
1574of a constant. For this purpose, numerical constants may be written
1575with an exponent marker that indicates the desired precision of the
1576inexact representation. The letters s, f, d, and l specify the use of
1577short, single, double, and long precision, respectively. (When fewer
1578than four internal inexact representations exist, the four size
1579specifications are mapped onto those available. For example, an
1580implementation with two internal representations may map short and
1581single together and long and double together.) In addition, the
1582exponent marker e specifies the default precision for the
1583implementation. The default precision has at least as much precision as
1584double, but implementations may wish to allow this default to be set by
1585the user.
1586
1587 3.14159265358979F0
1588         Round to single --- 3.141593
1589 0.6L0
1590         Extend to long --- .600000000000000
1591
1592==== Numerical operations
1593
1594The numerical routines described below have argument restrictions,
1595which are encoded in the naming conventions of the arguments as
1596given in the procedure's signature.  The conventions are as follows:
1597
1598; {{obj}} : any object
1599; {{list, list1, ... listj, ...	list : (see "[[#Pairs_and_lists|Pairs and lists]]" below)
1600; {{z, z1, ... zj, ...}} : complex number
1601; {{x, x1, ... xj, ...}} : real number
1602; {{y, y1, ... yj, ...}} : real number
1603; {{q, q1, ... qj, ...}} : rational number 
1604; {{n, n1, ... nj, ...}} : integer
1605; {{k, k1, ... kj, ...}} : exact non-negative integer
1606
1607The examples used in this section assume that any
1608numerical constant written using an exact notation is indeed
1609represented as an exact number. Some examples also assume that certain
1610numerical constants written using an inexact notation can be
1611represented without loss of accuracy; the inexact constants were chosen
1612so that this is likely to be true in implementations that use flonums
1613to represent inexact numbers.
1614
1615<procedure>(number? obj)</procedure><br>
1616<procedure>(complex? obj)</procedure><br>
1617<procedure>(real? obj)</procedure><br>
1618<procedure>(rational? obj)</procedure><br>
1619<procedure>(integer? obj)</procedure><br>
1620
1621These numerical type predicates can be applied to any kind of argument,
1622including non-numbers. They return #t if the object is of the named
1623type, and otherwise they return #f. In general, if a type predicate is
1624true of a number then all higher type predicates are also true of that
1625number. Consequently, if a type predicate is false of a number, then
1626all lower type predicates are also false of that number. If z is an
1627inexact complex number, then (real? z) is true if and only if (zero?
1628(imag-part z)) is true. If x is an inexact real number, then (integer?
1629x) is true if and only if (= x (round x)).
1630
1631 (complex? 3+4i)                 ===>  #t
1632 (complex? 3)                    ===>  #t
1633 (real? 3)                       ===>  #t
1634 (real? -2.5+0.0i)               ===>  #t
1635 (real? #e1e10)                  ===>  #t
1636 (rational? 6/10)                ===>  #t
1637 (rational? 6/3)                 ===>  #t
1638 (integer? 3+0i)                 ===>  #t
1639 (integer? 3.0)                  ===>  #t
1640 (integer? 8/4)                  ===>  #t
1641
1642Note:   The behavior of these type predicates on inexact numbers is
1643unreliable, since any inaccuracy may affect the result.
1644
1645Note:   In many implementations the rational? procedure will be the
1646same as real?, and the complex? procedure will be the same as
1647number?, but unusual implementations may be able to represent some
1648irrational numbers exactly or may extend the number system to
1649support some kind of non-complex numbers.
1650
1651<procedure>(exact? z)</procedure><br>
1652<procedure>(inexact? z)</procedure><br>
1653
1654These numerical predicates provide tests for the exactness of a
1655quantity. For any Scheme number, precisely one of these predicates is
1656true.
1657
1658<procedure>(= z[1] z[2] z[3] ...)</procedure><br>
1659<procedure>(< x[1] x[2] x[3] ...)</procedure><br>
1660<procedure>(> x[1] x[2] x[3] ...)</procedure><br>
1661<procedure>(<= x[1] x[2] x[3] ...)</procedure><br>
1662<procedure>(>= x[1] x[2] x[3] ...)</procedure><br>
1663
1664These procedures return #t if their arguments are (respectively):
1665equal, monotonically increasing, monotonically decreasing,
1666monotonically nondecreasing, or monotonically nonincreasing.
1667
1668These predicates are required to be transitive.
1669
1670Note:   The traditional implementations of these predicates in
1671Lisp-like languages are not transitive.
1672
1673Note:   While it is not an error to compare inexact numbers using
1674these predicates, the results may be unreliable because a small
1675inaccuracy may affect the result; this is especially true of = and
1676zero?. When in doubt, consult a numerical analyst.
1677
1678<procedure>(zero? z)</procedure><br>
1679<procedure>(positive? x)</procedure><br>
1680<procedure>(negative? x)</procedure><br>
1681<procedure>(odd? n)</procedure><br>
1682<procedure>(even? n)</procedure><br>
1683
1684These numerical predicates test a number for a particular property,
1685returning #t or #f. See note above.
1686
1687<procedure>(max x[1] x[2] ...)</procedure><br>
1688<procedure>(min x[1] x[2] ...)</procedure><br>
1689
1690These procedures return the maximum or minimum of their arguments.
1691
1692 (max 3 4)                      ===>  4    ; exact
1693 (max 3.9 4)                    ===>  4.0  ; inexact
1694
1695Note:   If any argument is inexact, then the result will also be
1696inexact (unless the procedure can prove that the inaccuracy is not
1697large enough to affect the result, which is possible only in
1698unusual implementations). If min or max is used to compare numbers
1699of mixed exactness, and the numerical value of the result cannot be
1700represented as an inexact number without loss of accuracy, then the
1701procedure may report a violation of an implementation restriction.
1702
1703<procedure>(+ z[1] ...)</procedure><br>
1704<procedure>(* z[1] ...)</procedure><br>
1705
1706These procedures return the sum or product of their arguments.
1707
1708 (+ 3 4)                         ===>  7
1709 (+ 3)                           ===>  3
1710 (+)                             ===>  0
1711 (* 4)                           ===>  4
1712 (*)                             ===>  1
1713
1714<procedure>(- z[1] z[2])</procedure><br>
1715<procedure>(- z)</procedure><br>
1716<procedure>(- z[1] z[2] ...)</procedure><br>
1717<procedure>(/ z[1] z[2])</procedure><br>
1718<procedure>(/ z)</procedure><br>
1719<procedure>(/ z[1] z[2] ...)</procedure><br>
1720
1721With two or more arguments, these procedures return the difference or
1722quotient of their arguments, associating to the left. With one
1723argument, however, they return the additive or multiplicative inverse
1724of their argument.
1725
1726 (- 3 4)                         ===>  -1
1727 (- 3 4 5)                       ===>  -6
1728 (- 3)                           ===>  -3
1729 (/ 3 4 5)                       ===>  3/20
1730 (/ 3)                           ===>  1/3
1731
1732<procedure>(abs x)</procedure><br>
1733
1734Abs returns the absolute value of its argument.
1735
1736 (abs -7)                        ===>  7
1737
1738<procedure>(quotient n[1] n[2])</procedure><br>
1739<procedure>(remainder n[1] n[2])</procedure><br>
1740<procedure>(modulo n[1] n[2])</procedure><br>
1741
1742These procedures implement number-theoretic (integer) division. n[2]
1743should be non-zero. All three procedures return integers. If n[1]/n[2]
1744is an integer:
1745
1746    (quotient n[1] n[2])           ===> n[1]/n[2]
1747    (remainder n[1] n[2])          ===> 0
1748    (modulo n[1] n[2])             ===> 0
1749
1750If n[1]/n[2] is not an integer:
1751
1752    (quotient n[1] n[2])           ===> n[q]
1753    (remainder n[1] n[2])          ===> n[r]
1754    (modulo n[1] n[2])             ===> n[m]
1755
1756where n[q] is n[1]/n[2] rounded towards zero, 0 < |n[r]| < |n[2]|, 0 <
1757|n[m]| < |n[2]|, n[r] and n[m] differ from n[1] by a multiple of n[2],
1758n[r] has the same sign as n[1], and n[m] has the same sign as n[2].
1759
1760From this we can conclude that for integers n[1] and n[2] with n[2] not
1761equal to 0,
1762
1763     (= n[1] (+ (* n[2] (quotient n[1] n[2]))
1764           (remainder n[1] n[2])))
1765                                         ===>  #t
1766
1767provided all numbers involved in that computation are exact.
1768
1769 (modulo 13 4)                   ===>  1
1770 (remainder 13 4)                ===>  1
1771 
1772 (modulo -13 4)                  ===>  3
1773 (remainder -13 4)               ===>  -1
1774 
1775 (modulo 13 -4)                  ===>  -3
1776 (remainder 13 -4)               ===>  1
1777 
1778 (modulo -13 -4)                 ===>  -1
1779 (remainder -13 -4)              ===>  -1
1780 
1781 (remainder -13 -4.0)            ===>  -1.0  ; inexact
1782
1783<procedure>(gcd n[1] ...)</procedure><br>
1784<procedure>(lcm n[1] ...)</procedure><br>
1785
1786These procedures return the greatest common divisor or least common
1787multiple of their arguments. The result is always non-negative.
1788
1789 (gcd 32 -36)                    ===>  4
1790 (gcd)                           ===>  0
1791 (lcm 32 -36)                    ===>  288
1792 (lcm 32.0 -36)                  ===>  288.0  ; inexact
1793 (lcm)                           ===>  1
1794
1795<procedure>(numerator q)</procedure><br>
1796<procedure>(denominator q)</procedure><br>
1797
1798These procedures return the numerator or denominator of their argument;
1799the result is computed as if the argument was represented as a fraction
1800in lowest terms. The denominator is always positive. The denominator of
18010 is defined to be 1.
1802
1803 (numerator (/ 6 4))            ===>  3
1804 (denominator (/ 6 4))          ===>  2
1805 (denominator
1806   (exact->inexact (/ 6 4)))    ===> 2.0
1807
1808<procedure>(floor x)</procedure><br>
1809<procedure>(ceiling x)</procedure><br>
1810<procedure>(truncate x)</procedure><br>
1811<procedure>(round x)</procedure><br>
1812
1813These procedures return integers. Floor returns the largest integer not
1814larger than x. Ceiling returns the smallest integer not smaller than x.
1815Truncate returns the integer closest to x whose absolute value is not
1816larger than the absolute value of x. Round returns the closest integer
1817to x, rounding to even when x is halfway between two integers.
1818
1819Rationale:   Round rounds to even for consistency with the default
1820rounding mode specified by the IEEE floating point standard.
1821
1822Note:   If the argument to one of these procedures is inexact, then
1823the result will also be inexact. If an exact value is needed, the
1824result should be passed to the inexact->exact procedure.
1825
1826 (floor -4.3)                  ===>  -5.0
1827 (ceiling -4.3)                ===>  -4.0
1828 (truncate -4.3)               ===>  -4.0
1829 (round -4.3)                  ===>  -4.0
1830 
1831 (floor 3.5)                   ===>  3.0
1832 (ceiling 3.5)                 ===>  4.0
1833 (truncate 3.5)                ===>  3.0
1834 (round 3.5)                   ===>  4.0  ; inexact
1835 
1836 (round 7/2)                   ===>  4    ; exact
1837 (round 7)                     ===>  7
1838
1839<procedure>(rationalize x y)</procedure><br>
1840
1841Rationalize returns the simplest rational number differing from x by no
1842more than y. A rational number r[1] is simpler than another rational
1843number r[2] if r[1] = p[1]/q[1] and r[2] = p[2]/q[2] (in lowest terms)
1844and |p[1]| < |p[2]| and |q[1]| < |q[2]|. Thus 3/5 is simpler than 4/7.
1845Although not all rationals are comparable in this ordering (consider 2/
18467 and 3/5) any interval contains a rational number that is simpler than
1847every other rational number in that interval (the simpler 2/5 lies
1848between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of
1849all.
1850
1851 (rationalize
1852   (inexact->exact .3) 1/10)          ===> 1/3    ; exact
1853 (rationalize .3 1/10)                ===> #i1/3  ; inexact
1854
1855<procedure>(exp z)</procedure><br>
1856<procedure>(log z)</procedure><br>
1857<procedure>(sin z)</procedure><br>
1858<procedure>(cos z)</procedure><br>
1859<procedure>(tan z)</procedure><br>
1860<procedure>(asin z)</procedure><br>
1861<procedure>(acos z)</procedure><br>
1862<procedure>(atan z)</procedure><br>
1863<procedure>(atan y x)</procedure><br>
1864
1865These procedures are part of every implementation that supports general
1866real numbers; they compute the usual transcendental functions. Log
1867computes the natural logarithm of z (not the base ten logarithm). Asin,
1868acos, and atan compute arcsine (sin^-1), arccosine (cos^-1), and
1869arctangent (tan^-1), respectively. The two-argument variant of atan
1870computes (angle (make-rectangular x y)) (see below), even in
1871implementations that don't support general complex numbers.
1872
1873In general, the mathematical functions log, arcsine, arccosine, and
1874arctangent are multiply defined. The value of log z is defined to be
1875the one whose imaginary part lies in the range from -pi
1876(exclusive) to pi (inclusive). log 0 is undefined. With log
1877defined this way, the values of sin^-1 z, cos^-1 z, and tan^-1 z are
1878according to the following formulae:
1879
1880 sin^-1 z = - i log (i z + (1 - z^2)^1/2)
1881 
1882 cos^-1 z = pi / 2 - sin^-1 z
1883 
1884 tan^-1 z = (log (1 + i z) - log (1 - i z)) / (2 i)
1885
1886The above specification follows [27], which in turn cites [19]; refer
1887to these sources for more detailed discussion of branch cuts, boundary
1888conditions, and implementation of these functions. When it is possible
1889these procedures produce a real result from a real argument.
1890
1891<procedure>(sqrt z)</procedure><br>
1892
1893Returns the principal square root of z. The result will have either
1894positive real part, or zero real part and non-negative imaginary part.
1895
1896<procedure>(expt z[1] z[2])</procedure><br>
1897
1898Returns z[1] raised to the power z[2]. For z[1] != 0
1899
1900 z[1]^z[2] = e^z[2] log z[1]
1901
19020^z is 1 if z = 0 and 0 otherwise.
1903
1904<procedure>(make-rectangular x[1] x[2])</procedure><br>
1905<procedure>(make-polar x[3] x[4])</procedure><br>
1906<procedure>(real-part z)</procedure><br>
1907<procedure>(imag-part z)</procedure><br>
1908<procedure>(magnitude z)</procedure><br>
1909<procedure>(angle z)</procedure><br>
1910
1911These procedures are part of every implementation that supports general
1912complex numbers. Suppose x[1], x[2], x[3], and x[4] are real numbers
1913and z is a complex number such that
1914
1915 z = x[1] + x[2]i = x[3] . e^i x[4]
1916
1917Then
1918
1919 (make-rectangular x[1] x[2])         ===> z
1920 (make-polar x[3] x[4])             ===> z
1921 (real-part z)                          ===> x[1]
1922 (imag-part z)                          ===> x[2]
1923 (magnitude z)                          ===> |x[3]|
1924 (angle z)                              ===> x[angle]
1925
1926where - pi < x[angle] < pi with x[angle] = x[4] + 2 pi n
1927for some integer n.
1928
1929Rationale:   Magnitude is the same as abs for a real argument, but
1930abs must be present in all implementations, whereas magnitude need
1931only be present in implementations that support general complex
1932numbers.
1933
1934<procedure>(exact->inexact z)</procedure><br>
1935<procedure>(inexact->exact z)</procedure><br>
1936
1937Exact->inexact returns an inexact representation of z. The value
1938returned is the inexact number that is numerically closest to the
1939argument. If an exact argument has no reasonably close inexact
1940equivalent, then a violation of an implementation restriction may be
1941reported.
1942
1943Inexact->exact returns an exact representation of z. The value returned
1944is the exact number that is numerically closest to the argument. If an
1945inexact argument has no reasonably close exact equivalent, then a
1946violation of an implementation restriction may be reported.
1947
1948These procedures implement the natural one-to-one correspondence
1949between exact and inexact integers throughout an
1950implementation-dependent range.
1951See "[[#implementation-restrictions|Implementation restrictions]]".
1952
1953==== Numerical input and output
1954
1955<procedure>(number->string z [radix])</procedure>
1956
1957Radix must be an exact integer.  The R5RS standard only requires
1958implementations to support 2, 8, 10, or 16, but CHICKEN allows any
1959radix between 2 and 36, inclusive (note: a bug in CHICKEN 5 currently 
1960limits the upper bound to 16).  If omitted, radix defaults to
196110. The procedure number->string takes a number and a radix and
1962returns as a string an external representation of the given number in
1963the given radix such that
1964
1965 (let ((number number)
1966       (radix radix))
1967   (eqv? number
1968         (string->number (number->string number
1969                                         radix)
1970                         radix)))
1971
1972is true. It is an error if no possible result makes this expression
1973true.
1974
1975If z is inexact, the radix is 10, and the above expression can be
1976satisfied by a result that contains a decimal point, then the result
1977contains a decimal point and is expressed using the minimum number of
1978digits (exclusive of exponent and trailing zeroes) needed to make the
1979above expression true [3, 5]; otherwise the format of the result is
1980unspecified.
1981
1982The result returned by number->string never contains an explicit radix
1983prefix.
1984
1985Note:   The error case can occur only when z is not a complex
1986number or is a complex number with a non-rational real or imaginary
1987part.
1988
1989Rationale:   If z is an inexact number represented using flonums,
1990and the radix is 10, then the above expression is normally
1991satisfied by a result containing a decimal point. The unspecified
1992case allows for infinities, NaNs, and non-flonum representations.
1993
1994As an extension to R5RS, CHICKEN supports reading and writing the
1995special IEEE floating-point numbers ''+nan'', ''+inf'' and ''-inf'',
1996as well as negative zero.
1997
1998<procedure>(string->number string)</procedure><br>
1999<procedure>(string->number string radix)</procedure><br>
2000
2001Returns a number of the maximally precise representation expressed by
2002the given string.  Radix must be an exact integer.  The R5RS standard
2003only requires implementations to support 2, 8, 10, or 16, but CHICKEN
2004allows any radix between 2 and 36, inclusive.  If supplied, radix is a
2005default radix that may be overridden by an explicit radix prefix in
2006string (e.g. "#o177"). If radix is not supplied, then the default
2007radix is 10. If string is not a syntactically valid notation for a
2008number, then string->number returns #f.
2009
2010 (string->number "100")                ===>  100
2011 (string->number "100" 16)             ===>  256
2012 (string->number "1e2")                ===>  100.0
2013 (string->number "15##")               ===>  1500.0
2014
2015Note:   The domain of string->number may be restricted by
2016implementations in the following ways. String->number is permitted
2017to return #f whenever string contains an explicit radix prefix. If
2018all numbers supported by an implementation are real, then string->
2019number is permitted to return #f whenever string uses the polar or
2020rectangular notations for complex numbers. If all numbers are
2021integers, then string->number may return #f whenever the fractional
2022notation is used. If all numbers are exact, then string->number may
2023return #f whenever an exponent marker or explicit exactness prefix
2024is used, or if a # appears in place of a digit. If all inexact
2025numbers are integers, then string->number may return #f whenever a
2026decimal point is used.
2027
2028As an extension to R5RS, CHICKEN supports reading and writing the
2029special IEEE floating-point numbers ''+nan'', ''+inf'' and ''-inf'',
2030as well as negative zero.
2031
2032=== Other data types
2033
2034This section describes operations on some of Scheme's non-numeric data
2035types: booleans, pairs, lists, symbols, characters, strings and
2036vectors.
2037
2038==== Booleans
2039
2040The standard boolean objects for true and false are written as #t and #f.
2041What really matters, though, are the objects that the Scheme
2042conditional expressions (if, cond, and, or, do) treat as true or false.
2043The phrase "a true value" (or sometimes just "true") means any
2044object treated as true by the conditional expressions, and the phrase
2045"a false value" (or "false") means any object treated as false by
2046the conditional expressions.
2047
2048Of all the standard Scheme values, only #f counts as false in
2049conditional expressions. Except for #f, all standard Scheme values,
2050including #t, pairs, the empty list, symbols, numbers, strings,
2051vectors, and procedures, count as true.
2052
2053Note:   Programmers accustomed to other dialects of Lisp should be
2054aware that Scheme distinguishes both #f and the empty list from the
2055symbol nil.
2056
2057Boolean constants evaluate to themselves, so they do not need to be
2058quoted in programs.
2059
2060 #t                ===>  #t
2061 #f                ===>  #f
2062 '#f               ===>  #f
2063
2064<procedure>(not obj)</procedure><br>
2065
2066Not returns #t if obj is false, and returns #f otherwise.
2067
2068 (not #t)           ===>  #f
2069 (not 3)            ===>  #f
2070 (not (list 3))     ===>  #f
2071 (not #f)           ===>  #t
2072 (not '())          ===>  #f
2073 (not (list))       ===>  #f
2074 (not 'nil)         ===>  #f
2075
2076<procedure>(boolean? obj)</procedure><br>
2077
2078Boolean? returns #t if obj is either #t or #f and returns #f otherwise.
2079
2080 (boolean? #f)                 ===>  #t
2081 (boolean? 0)                  ===>  #f
2082 (boolean? '())                ===>  #f
2083
2084==== Pairs and lists
2085
2086A pair (sometimes called a dotted pair) is a record structure with two
2087fields called the car and cdr fields (for historical reasons). Pairs
2088are created by the procedure cons. The car and cdr fields are accessed
2089by the procedures car and cdr. The car and cdr fields are assigned by
2090the procedures set-car! and set-cdr!.
2091
2092Pairs are used primarily to represent lists. A list can be defined
2093recursively as either the empty list or a pair whose cdr is a list.
2094More precisely, the set of lists is defined as the smallest set X such
2095that
2096
2097*   The empty list is in X.
2098*   If list is in X, then any pair whose cdr field contains list is
2099    also in X.
2100
2101The objects in the car fields of successive pairs of a list are the
2102elements of the list. For example, a two-element list is a pair whose
2103car is the first element and whose cdr is a pair whose car is the
2104second element and whose cdr is the empty list. The length of a list is
2105the number of elements, which is the same as the number of pairs.
2106
2107The empty list is a special object of its own type (it is not a pair);
2108it has no elements and its length is zero.
2109
2110Note:   The above definitions imply that all lists have finite
2111length and are terminated by the empty list.
2112
2113The most general notation (external representation) for Scheme pairs is
2114the "dotted" notation (c[1] . c[2]) where c[1] is the value of the
2115car field and c[2] is the value of the cdr field. For example (4 . 5)
2116is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the
2117external representation of a pair, not an expression that evaluates to
2118a pair.
2119
2120A more streamlined notation can be used for lists: the elements of the
2121list are simply enclosed in parentheses and separated by spaces. The
2122empty list is written () . For example,
2123
2124 (a b c d e)
2125
2126and
2127
2128 (a . (b . (c . (d . (e . ())))))
2129
2130are equivalent notations for a list of symbols.
2131
2132A chain of pairs not ending in the empty list is called an improper
2133list. Note that an improper list is not a list. The list and dotted
2134notations can be combined to represent improper lists:
2135
2136 (a b c . d)
2137
2138is equivalent to
2139
2140 (a . (b . (c . d)))
2141
2142Whether a given pair is a list depends upon what is stored in the cdr
2143field. When the set-cdr! procedure is used, an object can be a list one
2144moment and not the next:
2145
2146 (define x (list 'a 'b 'c))
2147 (define y x)
2148 y                               ===>  (a b c)
2149 (list? y)                       ===>  #t
2150 (set-cdr! x 4)                  ===>  unspecified
2151 x                               ===>  (a . 4)
2152 (eqv? x y)                      ===>  #t
2153 y                               ===>  (a . 4)
2154 (list? y)                       ===>  #f
2155 (set-cdr! x x)                  ===>  unspecified
2156 (list? x)                       ===>  #f
2157
2158Within literal expressions and representations of objects read by the
2159read procedure, the forms '<datum>, `<datum>, ,<datum>, and ,@<datum>
2160denote two-element lists whose first elements are the symbols quote,
2161quasiquote, unquote, and unquote-splicing, respectively. The second
2162element in each case is <datum>. This convention is supported so that
2163arbitrary Scheme programs may be represented as lists. That is,
2164according to Scheme's grammar, every <expression> is also a <datum>.
2165Among other things, this permits the use of the read procedure to
2166parse Scheme programs.
2167
2168<procedure>(pair? obj)</procedure><br>
2169
2170Pair? returns #t if obj is a pair, and otherwise returns #f.
2171NOTE: [[Module (chicken base)#weak-pairs|Weak pairs]] are regarded
2172as pairs by this procedure.
2173
2174 (pair? '(a . b))                ===>  #t
2175 (pair? '(a b c))                ===>  #t
2176 (pair? '())                     ===>  #f
2177 (pair? '#(a b))                 ===>  #f
2178 (pair? (cons 1 2))              ===>  #t
2179 
2180 (import (chicken base))
2181 (pair? (weak-cons 1 2))         ===>  #t
2182
2183<procedure>(cons obj[1] obj[2])</procedure><br>
2184
2185Returns a newly allocated pair whose car is obj[1] and whose cdr is
2186obj[2]. The pair is guaranteed to be different (in the sense of eqv?)
2187from every existing object.
2188
2189 (cons 'a '())                   ===>  (a)
2190 (cons '(a) '(b c d))            ===>  ((a) b c d)
2191 (cons "a" '(b c))               ===>  ("a" b c)
2192 (cons 'a 3)                     ===>  (a . 3)
2193 (cons '(a b) 'c)                ===>  ((a b) . c)
2194
2195<procedure>(car pair)</procedure><br>
2196
2197Returns the contents of the car field of pair. Note that it is an error
2198to take the car of the empty list.
2199
2200 (car '(a b c))                  ===>  a
2201 (car '((a) b c d))              ===>  (a)
2202 (car '(1 . 2))                  ===>  1
2203 (car '())                       ===>  error
2204 (car (cons 1 2))                ===>  1
2205 
2206 (import (chicken base))
2207 (car (weak-cons 1 2))           ===>  1
2208
2209<procedure>(cdr pair)</procedure><br>
2210
2211Returns the contents of the cdr field of pair. Note that it is an error
2212to take the cdr of the empty list.
2213
2214 (cdr '((a) b c d))              ===>  (b c d)
2215 (cdr '(1 . 2))                  ===>  2
2216 (cdr '())                       ===>  error
2217 (cdr (cons 1 2))                ===>  2
2218 
2219 (import (chicken base))
2220 (cdr (weak-cons 1 2))           ===>  2
2221
2222<procedure>(set-car! pair obj)</procedure><br>
2223
2224Stores obj in the car field of pair. The value returned by set-car! is
2225unspecified.
2226
2227 (define (f) (list 'not-a-constant-list))
2228 (define (g) '(constant-list))
2229 (set-car! (f) 3)                     ===>  unspecified
2230 (set-car! (g) 3)                     ===>  error
2231
2232<procedure>(set-cdr! pair obj)</procedure><br>
2233
2234Stores obj in the cdr field of pair. The value returned by set-cdr! is
2235unspecified.
2236
2237<procedure>(caar pair)</procedure><br>
2238<procedure>(cadr pair)</procedure><br>
2239<procedure>(cdar pair)</procedure><br>
2240<procedure>(cddr pair)</procedure><br>
2241<procedure>(caaar pair)</procedure><br>
2242<procedure>(caadr pair)</procedure><br>
2243<procedure>(cadar pair)</procedure><br>
2244<procedure>(caddr pair)</procedure><br>
2245<procedure>(cdaar pair)</procedure><br>
2246<procedure>(cdadr pair)</procedure><br>
2247<procedure>(cddar pair)</procedure><br>
2248<procedure>(cdddr pair)</procedure><br>
2249<procedure>(caaaar pair)</procedure><br>
2250<procedure>(caaadr pair)</procedure><br>
2251<procedure>(caadar pair)</procedure><br>
2252<procedure>(caaddr pair)</procedure><br>
2253<procedure>(cadaar pair)</procedure><br>
2254<procedure>(cadadr pair)</procedure><br>
2255<procedure>(caddar pair)</procedure><br>
2256<procedure>(cadddr pair)</procedure><br>
2257<procedure>(cdaaar pair)</procedure><br>
2258<procedure>(cdaadr pair)</procedure><br>
2259<procedure>(cdadar pair)</procedure><br>
2260<procedure>(cdaddr pair)</procedure><br>
2261<procedure>(cddaar pair)</procedure><br>
2262<procedure>(cddadr pair)</procedure><br>
2263<procedure>(cdddar pair)</procedure><br>
2264<procedure>(cddddr pair)</procedure><br>
2265
2266These procedures are compositions of car and cdr, where for example
2267caddr could be defined by
2268
2269 (define caddr (lambda (x) (car (cdr (cdr x))))).
2270
2271<procedure>(null? obj)</procedure><br>
2272
2273Returns #t if obj is the empty list, otherwise returns #f.
2274
2275<procedure>(list? obj)</procedure><br>
2276
2277Returns #t if obj is a list, otherwise returns #f. By definition, all
2278lists have finite length and are terminated by the empty list.
2279
2280 (list? '(a b c))             ===>  #t
2281 (list? '())                  ===>  #t
2282 (list? '(a . b))             ===>  #f
2283 (let ((x (list 'a)))
2284   (set-cdr! x x)
2285   (list? x))                 ===>  #f
2286
2287<procedure>(list obj ...)</procedure><br>
2288
2289Returns a newly allocated list of its arguments.
2290
2291 (list 'a (+ 3 4) 'c)                    ===>  (a 7 c)
2292 (list)                                  ===>  ()
2293
2294<procedure>(length list)</procedure><br>
2295
2296Returns the length of list.
2297
2298 (length '(a b c))                       ===>  3
2299 (length '(a (b) (c d e)))               ===>  3
2300 (length '())                            ===>  0
2301
2302<procedure>(append list ...)</procedure><br>
2303
2304Returns a list consisting of the elements of the first list followed by
2305the elements of the other lists.
2306
2307 (append '(x) '(y))                      ===>  (x y)
2308 (append '(a) '(b c d))                  ===>  (a b c d)
2309 (append '(a (b)) '((c)))                ===>  (a (b) (c))
2310
2311The resulting list is always newly allocated, except that it shares
2312structure with the last list argument. The last argument may actually
2313be any object; an improper list results if the last argument is not a
2314proper list.
2315
2316 (append '(a b) '(c . d))                ===>  (a b c . d)
2317 (append '() 'a)                         ===>  a
2318
2319<procedure>(reverse list)</procedure><br>
2320
2321Returns a newly allocated list consisting of the elements of list in
2322reverse order.
2323
2324 (reverse '(a b c))                      ===>  (c b a)
2325 (reverse '(a (b c) d (e (f))))
2326                 ===>  ((e (f)) d (b c) a)
2327
2328<procedure>(list-tail list k)</procedure><br>
2329
2330Returns the sublist of list obtained by omitting the first k elements.
2331It is an error if list has fewer than k elements. List-tail could be
2332defined by
2333
2334 (define list-tail
2335   (lambda (x k)
2336     (if (zero? k)
2337         x
2338         (list-tail (cdr x) (- k 1)))))
2339
2340<procedure>(list-ref list k)</procedure><br>
2341
2342Returns the kth element of list. (This is the same as the car of
2343(list-tail list k).) It is an error if list has fewer than k elements.
2344
2345 (list-ref '(a b c d) 2)                ===>  c
2346 (list-ref '(a b c d)
2347           (inexact->exact (round 1.8))) 
2348                 ===>  c
2349
2350<procedure>(memq obj list)</procedure><br>
2351<procedure>(memv obj list)</procedure><br>
2352<procedure>(member obj list)</procedure><br>
2353
2354These procedures return the first sublist of list whose car is obj,
2355where the sublists of list are the non-empty lists returned by
2356(list-tail list k) for k less than the length of list. If obj does not
2357occur in list, then #f (not the empty list) is returned. Memq uses eq?
2358to compare obj with the elements of list, while memv uses eqv? and
2359member uses equal?.
2360
2361 (memq 'a '(a b c))                      ===>  (a b c)
2362 (memq 'b '(a b c))                      ===>  (b c)
2363 (memq 'a '(b c d))                      ===>  #f
2364 (memq (list 'a) '(b (a) c))             ===>  #f
2365 (member (list 'a)
2366         '(b (a) c))                     ===>  ((a) c)
2367 (memq 101 '(100 101 102))               ===>  unspecified
2368 (memv 101 '(100 101 102))               ===>  (101 102)
2369
2370<procedure>(assq obj alist)</procedure><br>
2371<procedure>(assv obj alist)</procedure><br>
2372<procedure>(assoc obj alist)</procedure><br>
2373
2374Alist (for "association list") must be a list of pairs. These
2375procedures find the first pair in alist whose car field is obj, and
2376returns that pair. If no pair in alist has obj as its car, then #f (not
2377the empty list) is returned. Assq uses eq? to compare obj with the car
2378fields of the pairs in alist, while assv uses eqv? and assoc uses
2379equal?.
2380
2381 (define e '((a 1) (b 2) (c 3)))
2382 (assq 'a e)             ===>  (a 1)
2383 (assq 'b e)             ===>  (b 2)
2384 (assq 'd e)             ===>  #f
2385 (assq (list 'a) '(((a)) ((b)) ((c))))
2386                         ===>  #f
2387 (assoc (list 'a) '(((a)) ((b)) ((c))))   
2388                                    ===>  ((a))
2389 (assq 5 '((2 3) (5 7) (11 13)))    
2390                                    ===>  unspecified
2391 (assv 5 '((2 3) (5 7) (11 13)))    
2392                                    ===>  (5 7)
2393
2394Rationale:   Although they are ordinarily used as predicates, memq,
2395memv, member, assq, assv, and assoc do not have question marks in
2396their names because they return useful values rather than just #t
2397or #f.
2398
2399==== Symbols
2400
2401Symbols are objects whose usefulness rests on the fact that two symbols
2402are identical (in the sense of eqv?) if and only if their names are
2403spelled the same way. This is exactly the property needed to represent
2404identifiers in programs, and so most implementations of Scheme use them
2405internally for that purpose. Symbols are useful for many other
2406applications; for instance, they may be used the way enumerated values
2407are used in Pascal.
2408
2409The rules for writing a symbol are exactly the same as the rules for
2410writing an identifier.
2411
2412It is guaranteed that any symbol that has been returned as part of a
2413literal expression, or read using the read procedure, and subsequently
2414written out using the write procedure, will read back in as the
2415identical symbol (in the sense of eqv?). The string->symbol procedure,
2416however, can create symbols for which this write/read invariance may
2417not hold because their names contain special characters or letters in
2418the non-standard case.
2419
2420Note:   Some implementations of Scheme have a feature known as
2421"slashification" in order to guarantee write/read invariance for
2422all symbols, but historically the most important use of this
2423feature has been to compensate for the lack of a string data type.
2424
2425Some implementations also have "uninterned symbols", which defeat
2426write/read invariance even in implementations with slashification,
2427and also generate exceptions to the rule that two symbols are the
2428same if and only if their names are spelled the same.
2429
2430<procedure>(symbol? obj)</procedure><br>
2431
2432Returns #t if obj is a symbol, otherwise returns #f.
2433
2434 (symbol? 'foo)                  ===>  #t
2435 (symbol? (car '(a b)))          ===>  #t
2436 (symbol? "bar")                 ===>  #f
2437 (symbol? 'nil)                  ===>  #t
2438 (symbol? '())                   ===>  #f
2439 (symbol? #f)                    ===>  #f
2440
2441<procedure>(symbol->string symbol)</procedure><br>
2442
2443Returns the name of symbol as a string. If the symbol was part of an
2444object returned as the value of a literal expression (see
2445"[[#literal-expressions|literal expressions]]") or by a call to the
2446read procedure, and its name contains alphabetic characters, then the
2447string returned will contain characters in the implementation's
2448preferred standard case -- some implementations will prefer upper
2449case, others lower case. If the symbol was returned by string->symbol,
2450the case of characters in the string returned will be the same as the
2451case in the string that was passed to string->symbol.  It is an error
2452to apply mutation procedures like string-set! to strings returned by
2453this procedure.
2454
2455The following examples assume that the implementation's standard case
2456is lower case:
2457
2458 (symbol->string 'flying-fish)     
2459                                           ===>  "flying-fish"
2460 (symbol->string 'Martin)                  ===>  "martin"
2461 (symbol->string
2462    (string->symbol "Malvina"))     
2463                                           ===>  "Malvina"
2464
2465<procedure>(string->symbol string)</procedure><br>
2466
2467Returns the symbol whose name is string. This procedure can create
2468symbols with names containing special characters or letters in the
2469non-standard case, but it is usually a bad idea to create such symbols
2470because in some implementations of Scheme they cannot be read as
2471themselves. See symbol->string.
2472
2473The following examples assume that the implementation's standard case
2474is lower case:
2475
2476 (eq? 'mISSISSIppi 'mississippi)  
2477                 ===>  #t
2478 (string->symbol "mISSISSIppi")  
2479                 ===>  the symbol with name "mISSISSIppi"
2480 (eq? 'bitBlt (string->symbol "bitBlt"))     
2481                 ===>  #f
2482 (eq? 'JollyWog
2483      (string->symbol
2484        (symbol->string 'JollyWog)))  
2485                 ===>  #t
2486 (string=? "K. Harper, M.D."
2487           (symbol->string
2488             (string->symbol "K. Harper, M.D.")))  
2489                 ===>  #t
2490
2491==== Characters
2492
2493Characters are objects that represent printed characters such as
2494letters and digits. Characters are written using the notation #\
2495<character> or #\<character name>. For example:
2496
2497 #\a       ; lower case letter
2498 #\A       ; upper case letter
2499 #\(       ; left parenthesis
2500 #\        ; the space character
2501 #\space   ; the preferred way to write a space
2502 #\newline ; the newline character
2503
2504Case is significant in #\<character>, but not in #\<character name>. If
2505<character> in #\<character> is alphabetic, then the character
2506following <character> must be a delimiter character such as a space or
2507parenthesis. This rule resolves the ambiguous case where, for example,
2508the sequence of characters "#\space" could be taken to be either a
2509representation of the space character or a representation of the
2510character "#\s" followed by a representation of the symbol "pace."
2511
2512Characters written in the #\ notation are self-evaluating. That is,
2513they do not have to be quoted in programs. Some of the procedures that
2514operate on characters ignore the difference between upper case and
2515lower case. The procedures that ignore case have "-ci" (for "case
2516insensitive") embedded in their names.
2517
2518<procedure>(char? obj)</procedure><br>
2519
2520Returns #t if obj is a character, otherwise returns #f.
2521
2522<procedure>(char=? char[1] char[2])</procedure><br>
2523<procedure>(char<? char[1] char[2])</procedure><br>
2524<procedure>(char>? char[1] char[2])</procedure><br>
2525<procedure>(char<=? char[1] char[2])</procedure><br>
2526<procedure>(char>=? char[1] char[2])</procedure><br>
2527
2528These procedures impose a total ordering on the set of characters. It
2529is guaranteed that under this ordering:
2530
2531*   The upper case characters are in order. For example, (char<? #\A #\
2532    B) returns #t.
2533*   The lower case characters are in order. For example, (char<? #\a #\
2534    b) returns #t.
2535*   The digits are in order. For example, (char<? #\0 #\9) returns #t.
2536*   Either all the digits precede all the upper case letters, or vice
2537    versa.
2538*   Either all the digits precede all the lower case letters, or vice
2539    versa.
2540
2541Some implementations may generalize these procedures to take more than
2542two arguments, as with the corresponding numerical predicates.
2543
2544<procedure>(char-ci=? char[1] char[2])</procedure><br>
2545<procedure>(char-ci<? char[1] char[2])</procedure><br>
2546<procedure>(char-ci>? char[1] char[2])</procedure><br>
2547<procedure>(char-ci<=? char[1] char[2])</procedure><br>
2548<procedure>(char-ci>=? char[1] char[2])</procedure><br>
2549
2550These procedures are similar to char=? et cetera, but they treat upper
2551case and lower case letters as the same. For example, (char-ci=? #\A #\
2552a) returns #t. Some implementations may generalize these procedures to
2553take more than two arguments, as with the corresponding numerical
2554predicates.
2555
2556<procedure>(char-alphabetic? char)</procedure><br>
2557<procedure>(char-numeric? char)</procedure><br>
2558<procedure>(char-whitespace? char)</procedure><br>
2559<procedure>(char-upper-case? letter)</procedure><br>
2560<procedure>(char-lower-case? letter)</procedure><br>
2561
2562These procedures return #t if their arguments are alphabetic, numeric,
2563whitespace, upper case, or lower case characters, respectively,
2564otherwise they return #f. The following remarks, which are specific to
2565the ASCII character set, are intended only as a guide: The alphabetic
2566characters are the 52 upper and lower case letters. The numeric
2567characters are the ten decimal digits. The whitespace characters are
2568space, tab, line feed, form feed, and carriage return.
2569
2570<procedure>(char->integer char)</procedure><br>
2571<procedure>(integer->char n)</procedure><br>
2572
2573Given a character, char->integer returns an exact integer
2574representation of the character. Given an exact integer that is the
2575image of a character under char->integer, integer->char returns that
2576character. These procedures implement order-preserving isomorphisms
2577between the set of characters under the char<=? ordering and some
2578subset of the integers under the <= ordering. That is, if
2579
2580 (char<=? a b) ===> #t  and  (<= x y) ===> #t
2581
2582and x and y are in the domain of integer->char, then
2583
2584 (<= (char->integer a)
2585     (char->integer b))                  ===>  #t
2586 
2587 (char<=? (integer->char x)
2588          (integer->char y))             ===>  #t
2589
2590Note that {{integer->char}} does currently not detect
2591a negative argument and will quietly convert {{-1}} to
2592{{#x1ffff}} in CHICKEN.
2593
2594<procedure>(char-upcase char)</procedure><br>
2595<procedure>(char-downcase char)</procedure><br>
2596
2597These procedures return a character char[2] such that (char-ci=? char
2598char[2]). In addition, if char is alphabetic, then the result of
2599char-upcase is upper case and the result of char-downcase is lower
2600case.
2601
2602==== Strings
2603
2604Strings are sequences of characters. Strings are written as sequences
2605of characters enclosed within doublequotes ("). A doublequote can be
2606written inside a string only by escaping it with a backslash (\), as in
2607
2608"The word \"recursion\" has many meanings."
2609
2610A backslash can be written inside a string only by escaping it with
2611another backslash. Scheme does not specify the effect of a backslash
2612within a string that is not followed by a doublequote or backslash.
2613
2614A string constant may continue from one line to the next, but the exact
2615contents of such a string are unspecified. The length of a string is
2616the number of characters that it contains. This number is an exact,
2617non-negative integer that is fixed when the string is created. The 
2618valid indexes of a string are the exact non-negative integers less than
2619the length of the string. The first character of a string has index 0,
2620the second has index 1, and so on.
2621
2622In phrases such as "the characters of string beginning with index
2623start and ending with index end," it is understood that the index
2624start is inclusive and the index end is exclusive. Thus if start and
2625end are the same index, a null substring is referred to, and if start
2626is zero and end is the length of string, then the entire string is
2627referred to.
2628
2629Some of the procedures that operate on strings ignore the difference
2630between upper and lower case. The versions that ignore case have
2631"-ci" (for "case insensitive") embedded in their names.
2632
2633<procedure>(string? obj)</procedure><br>
2634
2635Returns #t if obj is a string, otherwise returns #f.
2636
2637<procedure>(make-string k)</procedure><br>
2638<procedure>(make-string k char)</procedure><br>
2639
2640Make-string returns a newly allocated string of length k. If char is
2641given, then all elements of the string are initialized to char,
2642otherwise the contents of the string are unspecified.
2643
2644<procedure>(string char ...)</procedure><br>
2645
2646Returns a newly allocated string composed of the arguments.
2647
2648<procedure>(string-length string)</procedure><br>
2649
2650Returns the number of characters in the given string.
2651
2652<procedure>(string-ref string k)</procedure><br>
2653
2654k must be a valid index of string. String-ref returns character k of
2655string using zero-origin indexing.
2656
2657<procedure>(string-set! string k char)</procedure><br>
2658
2659k must be a valid index of string. String-set! stores char in element k
2660of string and returns an unspecified value.
2661
2662 (define (f) (make-string 3 #\*))
2663 (define (g) "***")
2664 (string-set! (f) 0 #\?)          ===>  unspecified
2665 (string-set! (g) 0 #\?)          ===>  error
2666 (string-set! (symbol->string 'immutable)
2667              0
2668              #\?)          ===>  error
2669
2670<procedure>(string=? string[1] string[2])</procedure><br>
2671<procedure>(string-ci=? string[1] string[2])</procedure><br>
2672
2673Returns #t if the two strings are the same length and contain the same
2674characters in the same positions, otherwise returns #f. String-ci=?
2675treats upper and lower case letters as though they were the same
2676character, but string=? treats upper and lower case as distinct
2677characters.
2678
2679<procedure>(string<? string[1] string[2])</procedure><br>
2680<procedure>(string>? string[1] string[2])</procedure><br>
2681<procedure>(string<=? string[1] string[2])</procedure><br>
2682<procedure>(string>=? string[1] string[2])</procedure><br>
2683<procedure>(string-ci<? string[1] string[2])</procedure><br>
2684<procedure>(string-ci>? string[1] string[2])</procedure><br>
2685<procedure>(string-ci<=? string[1] string[2])</procedure><br>
2686<procedure>(string-ci>=? string[1] string[2])</procedure><br>
2687
2688These procedures are the lexicographic extensions to strings of the
2689corresponding orderings on characters. For example, string<? is the
2690lexicographic ordering on strings induced by the ordering char<? on
2691characters. If two strings differ in length but are the same up to the
2692length of the shorter string, the shorter string is considered to be
2693lexicographically less than the longer string.
2694
2695Implementations may generalize these and the string=? and string-ci=?
2696procedures to take more than two arguments, as with the corresponding
2697numerical predicates.
2698
2699<procedure>(substring string start [end])</procedure><br>
2700
2701String must be a string, and start and end must be exact integers
2702satisfying
2703
2704 0 <= start <= end <= (string-length string)
2705
2706Substring returns a newly allocated string formed from the characters
2707of string beginning with index start (inclusive) and ending with index
2708end (exclusive). The {{end}} argument is optional and defaults to the
2709length of the string, this is a non-standard extension in CHICKEN.
2710
2711<procedure>(string-append string ...)</procedure><br>
2712
2713Returns a newly allocated string whose characters form the
2714concatenation of the given strings.
2715
2716<procedure>(string->list string)</procedure><br>
2717<procedure>(list->string list)</procedure><br>
2718
2719String->list returns a newly allocated list of the characters that make
2720up the given string. List->string returns a newly allocated string
2721formed from the characters in the list list, which must be a list of
2722characters. String->list and list->string are inverses so far as equal?
2723is concerned.
2724
2725<procedure>(string-copy string)</procedure><br>
2726
2727Returns a newly allocated copy of the given string.
2728
2729<procedure>(string-fill! string char)</procedure><br>
2730
2731Stores char in every element of the given string and returns an
2732unspecified value.
2733
2734==== Vectors
2735
2736Vectors are heterogenous structures whose elements are indexed by
2737integers. A vector typically occupies less space than a list of the
2738same length, and the average time required to access a randomly chosen
2739element is typically less for the vector than for the list.
2740
2741The length of a vector is the number of elements that it contains. This
2742number is a non-negative integer that is fixed when the vector is
2743created. The valid indexes of a vector are the exact non-negative
2744integers less than the length of the vector. The first element in a
2745vector is indexed by zero, and the last element is indexed by one less
2746than the length of the vector.
2747
2748Vectors are written using the notation #(obj ...). For example, a
2749vector of length 3 containing the number zero in element 0, the list (2
27502 2 2) in element 1, and the string "Anna" in element 2 can be written
2751as following:
2752
2753 #(0 (2 2 2 2) "Anna")
2754
2755Note that this is the external representation of a vector, not an
2756expression evaluating to a vector. Like list constants, vector
2757constants must be quoted:
2758
2759 '#(0 (2 2 2 2) "Anna")  
2760                 ===>  #(0 (2 2 2 2) "Anna")
2761
2762<procedure>(vector? obj)</procedure><br>
2763
2764Returns #t if obj is a vector, otherwise returns #f.
2765
2766<procedure>(make-vector k)</procedure><br>
2767<procedure>(make-vector k fill)</procedure><br>
2768
2769Returns a newly allocated vector of k elements. If a second argument is
2770given, then each element is initialized to fill. Otherwise the initial
2771contents of each element is unspecified.
2772
2773<procedure>(vector obj ...)</procedure><br>
2774
2775Returns a newly allocated vector whose elements contain the given
2776arguments. Analogous to list.
2777
2778 (vector 'a 'b 'c)                       ===>  #(a b c)
2779
2780<procedure>(vector-length vector)</procedure><br>
2781
2782Returns the number of elements in vector as an exact integer.
2783
2784<procedure>(vector-ref vector k)</procedure><br>
2785
2786k must be a valid index of vector. Vector-ref returns the contents of
2787element k of vector.
2788
2789 (vector-ref '#(1 1 2 3 5 8 13 21)
2790             5)  
2791                 ===>  8
2792 (vector-ref '#(1 1 2 3 5 8 13 21)
2793             (let ((i (round (* 2 (acos -1)))))
2794               (if (inexact? i)
2795                   (inexact->exact i)
2796                   i))) 
2797                 ===> 13
2798
2799<procedure>(vector-set! vector k obj)</procedure><br>
2800
2801k must be a valid index of vector. Vector-set! stores obj in element k
2802of vector. The value returned by vector-set! is unspecified.
2803
2804 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
2805   (vector-set! vec 1 '("Sue" "Sue"))
2806   vec)      
2807                 ===>  #(0 ("Sue" "Sue") "Anna")
2808 
2809 (vector-set! '#(0 1 2) 1 "doe")  
2810                 ===>  error  ; constant vector
2811
2812<procedure>(vector->list vector)</procedure><br>
2813<procedure>(list->vector list)</procedure><br>
2814
2815Vector->list returns a newly allocated list of the objects contained in
2816the elements of vector. List->vector returns a newly created vector
2817initialized to the elements of the list list.
2818
2819 (vector->list '#(dah dah didah))  
2820                 ===>  (dah dah didah)
2821 (list->vector '(dididit dah))   
2822                 ===>  #(dididit dah)
2823
2824<procedure>(vector-fill! vector fill)</procedure><br>
2825
2826Stores fill in every element of vector. The value returned by
2827vector-fill! is unspecified.
2828
2829=== Control features
2830
2831This chapter describes various primitive procedures which control the
2832flow of program execution in special ways. The procedure? predicate is
2833also described here.
2834
2835<procedure>(procedure? obj)</procedure><br>
2836
2837Returns #t if obj is a procedure, otherwise returns #f.
2838
2839 (procedure? car)                    ===>  #t
2840 (procedure? 'car)                   ===>  #f
2841 (procedure? (lambda (x) (* x x)))   
2842                                     ===>  #t
2843 (procedure? '(lambda (x) (* x x)))  
2844                                     ===>  #f
2845 (call-with-current-continuation procedure?)
2846                                     ===>  #t
2847
2848<procedure>(apply proc arg[1] ... args)</procedure><br>
2849
2850Proc must be a procedure and args must be a list. Calls proc with the
2851elements of the list (append (list arg[1] ...) args) as the actual
2852arguments.
2853
2854 (apply + (list 3 4))                      ===>  7
2855 
2856 (define compose
2857   (lambda (f g)
2858     (lambda args
2859       (f (apply g args)))))
2860 
2861 ((compose sqrt *) 12 75)                      ===>  30
2862
2863<procedure>(map proc list[1] list[2] ...)</procedure><br>
2864
2865The lists must be lists, and proc must be a procedure taking as many
2866arguments as there are lists and returning a single value. Map applies
2867proc element-wise to the elements of the lists and returns a list of
2868the results, in order. The dynamic order in which proc is applied to
2869the elements of the lists is unspecified.
2870
2871Like in SRFI-1, this procedure allows the arguments to be of unequal
2872length; it terminates when the shortest list runs out.  This is a
2873CHICKEN extension to R5RS.
2874
2875 (map cadr '((a b) (d e) (g h)))   
2876                 ===>  (b e h)
2877 
2878 (map (lambda (n) (expt n n))
2879      '(1 2 3 4 5))                
2880                 ===>  (1 4 27 256 3125)
2881 
2882 (map + '(1 2 3) '(4 5 6))                 ===>  (5 7 9)
2883 
2884 (let ((count 0))
2885   (map (lambda (ignored)
2886          (set! count (+ count 1))
2887          count)
2888        '(a b)))                         ===>  (1 2) or (2 1)
2889
2890<procedure>(for-each proc list[1] list[2] ...)</procedure><br>
2891
2892The arguments to for-each are like the arguments to map, but for-each
2893calls proc for its side effects rather than for its values. Unlike map,
2894for-each is guaranteed to call proc on the elements of the lists in
2895order from the first element(s) to the last, and the value returned by
2896for-each is unspecified.
2897
2898 (let ((v (make-vector 5)))
2899   (for-each (lambda (i)
2900               (vector-set! v i (* i i)))
2901             '(0 1 2 3 4))
2902   v)                                        ===>  #(0 1 4 9 16)
2903
2904Like in SRFI-1, this procedure allows the arguments to be of unequal
2905length; it terminates when the shortest list runs out.  This is a
2906CHICKEN extension to R5RS.
2907
2908<procedure>(force promise)</procedure><br>
2909
2910Forces the value of promise (see "[[#delayed-evaluation|delayed
2911evaluation]]"). If no value has been computed for the promise, then a
2912value is computed and returned.  The value of the promise is cached
2913(or "memoized") so that if it is forced a second time, the previously
2914computed value is returned.
2915
2916 (force (delay (+ 1 2)))           ===>  3
2917 (let ((p (delay (+ 1 2))))
2918   (list (force p) (force p)))  
2919                                        ===>  (3 3)
2920 
2921 (define a-stream
2922   (letrec ((next
2923             (lambda (n)
2924               (cons n (delay (next (+ n 1)))))))
2925     (next 0)))
2926 (define head car)
2927 (define tail
2928   (lambda (stream) (force (cdr stream))))
2929 
2930 (head (tail (tail a-stream)))  
2931                                        ===>  2
2932
2933Force and delay are mainly intended for programs written in functional
2934style. The following examples should not be considered to illustrate
2935good programming style, but they illustrate the property that only one
2936value is computed for a promise, no matter how many times it is forced.
2937
2938 (define count 0)
2939 (define p
2940   (delay (begin (set! count (+ count 1))
2941                 (if (> count x)
2942                     count
2943                     (force p)))))
2944 (define x 5)
2945 p                             ===>  a promise
2946 (force p)                     ===>  6
2947 p                             ===>  a promise, still
2948 (begin (set! x 10)
2949        (force p))             ===>  6
2950
2951Here is a possible implementation of delay and force. Promises are
2952implemented here as procedures of no arguments, and force simply calls
2953its argument:
2954
2955 (define force
2956   (lambda (object)
2957     (object)))
2958
2959We define the expression
2960
2961 (delay <expression>)
2962
2963to have the same meaning as the procedure call
2964
2965 (make-promise (lambda () <expression>))
2966
2967as follows
2968
2969 (define-syntax delay
2970   (syntax-rules ()
2971     ((delay expression)
2972      (make-promise (lambda () expression))))),
2973
2974where make-promise is defined as follows:
2975
2976 (define make-promise
2977   (lambda (proc)
2978     (let ((result-ready? #f)
2979           (result #f))
2980       (lambda ()
2981         (if result-ready?
2982             result
2983             (let ((x (proc)))
2984               (if result-ready?
2985                   result
2986                   (begin (set! result-ready? #t)
2987                          (set! result x)
2988                          result))))))))
2989
2990Rationale:   A promise may refer to its own value, as in the last
2991example above. Forcing such a promise may cause the promise to be
2992forced a second time before the value of the first force has been
2993computed. This complicates the definition of make-promise.
2994
2995Various extensions to this semantics of delay and force are supported
2996in some implementations:
2997
2998*   Calling force on an object that is not a promise may simply return
2999    the object (this is the case in CHICKEN).
3000
3001*   It may be the case that there is no means by which a promise can be
3002    operationally distinguished from its forced value. That is,
3003    expressions like the following may evaluate to either #t or to #f,
3004    depending on the implementation:
3005
3006    (eqv? (delay 1) 1)                  ===>  unspecified
3007    (pair? (delay (cons 1 2)))          ===>  unspecified
3008
3009    In CHICKEN, promises are separate objects, so the above expressions
3010    will both evaluate to {{#f}}.
3011
3012*   Some implementations may implement "implicit forcing," where the
3013    value of a promise is forced by primitive procedures like cdr and
3014    +:
3015
3016    (+ (delay (* 3 7)) 13)          ===>  34
3017
3018    This is '''not''' the case in CHICKEN.
3019
3020
3021<procedure>(call-with-current-continuation proc)</procedure><br>
3022
3023Proc must be a procedure of one argument. The procedure
3024call-with-current-continuation packages up the current continuation
3025(see the rationale below) as an "escape procedure" and passes it as
3026an argument to proc. The escape procedure is a Scheme procedure that,
3027if it is later called, will abandon whatever continuation is in effect
3028at that later time and will instead use the continuation that was in
3029effect when the escape procedure was created. Calling the escape
3030procedure may cause the invocation of before and after thunks installed
3031using dynamic-wind.
3032
3033The escape procedure accepts the same number of arguments as the
3034continuation to the original call to call-with-current-continuation.
3035Except for continuations created by the call-with-values procedure, all
3036continuations take exactly one value. The effect of passing no value or
3037more than one value to continuations that were not created by
3038call-with-values is unspecified.
3039
3040The escape procedure that is passed to proc has unlimited extent just
3041like any other procedure in Scheme. It may be stored in variables or
3042data structures and may be called as many times as desired.
3043
3044The following examples show only the most common ways in which
3045call-with-current-continuation is used. If all real uses were as simple
3046as these examples, there would be no need for a procedure with the
3047power of call-with-current-continuation.
3048
3049 (call-with-current-continuation
3050   (lambda (exit)
3051     (for-each (lambda (x)
3052                 (if (negative? x)
3053                     (exit x)))
3054               '(54 0 37 -3 245 19))
3055     #t))                                ===>  -3
3056 
3057 (define list-length
3058   (lambda (obj)
3059     (call-with-current-continuation
3060       (lambda (return)
3061         (letrec ((r
3062                   (lambda (obj)
3063                     (cond ((null? obj) 0)
3064                           ((pair? obj)
3065                            (+ (r (cdr obj)) 1))
3066                           (else (return #f))))))
3067           (r obj))))))
3068 
3069 (list-length '(1 2 3 4))                    ===>  4
3070 
3071 (list-length '(a b . c))                    ===>  #f
3072
3073Rationale:
3074
3075A common use of call-with-current-continuation is for structured,
3076non-local exits from loops or procedure bodies, but in fact
3077call-with-current-continuation is extremely useful for implementing
3078a wide variety of advanced control structures.
3079
3080Whenever a Scheme expression is evaluated there is a continuation
3081wanting the result of the expression. The continuation represents
3082an entire (default) future for the computation. If the expression
3083is evaluated at top level, for example, then the continuation might
3084take the result, print it on the screen, prompt for the next input,
3085evaluate it, and so on forever. Most of the time the continuation
3086includes actions specified by user code, as in a continuation that
3087will take the result, multiply it by the value stored in a local
3088variable, add seven, and give the answer to the top level
3089continuation to be printed. Normally these ubiquitous continuations
3090are hidden behind the scenes and programmers do not think much
3091about them. On rare occasions, however, a programmer may need to
3092deal with continuations explicitly. Call-with-current-continuation
3093allows Scheme programmers to do that by creating a procedure that
3094acts just like the current continuation.
3095
3096Most programming languages incorporate one or more special-purpose
3097escape constructs with names like exit, return, or even goto. In
30981965, however, Peter Landin [16] invented a general purpose escape
3099operator called the J-operator. John Reynolds [24] described a
3100simpler but equally powerful construct in 1972. The catch special
3101form described by Sussman and Steele in the 1975 report on Scheme
3102is exactly the same as Reynolds's construct, though its name came
3103from a less general construct in MacLisp. Several Scheme
3104implementors noticed that the full power of the catch construct
3105could be provided by a procedure instead of by a special syntactic
3106construct, and the name call-with-current-continuation was coined
3107in 1982. This name is descriptive, but opinions differ on the
3108merits of such a long name, and some people use the name call/cc
3109instead.
3110
3111<procedure>(values obj ...)</procedure><br>
3112
3113Delivers all of its arguments to its continuation. Except for
3114continuations created by the call-with-values procedure, all
3115continuations take exactly one value. Values might be defined as
3116follows:
3117
3118 (define (values . things)
3119   (call-with-current-continuation 
3120     (lambda (cont) (apply cont things))))
3121
3122<procedure>(call-with-values producer consumer)</procedure><br>
3123
3124Calls its producer argument with no values and a continuation that,
3125when passed some values, calls the consumer procedure with those values
3126as arguments. The continuation for the call to consumer is the
3127continuation of the call to call-with-values.
3128
3129 (call-with-values (lambda () (values 4 5))
3130                   (lambda (a b) b))
3131                                                            ===>  5
3132 
3133 (call-with-values * -)                                     ===>  -1
3134
3135<procedure>(dynamic-wind before thunk after)</procedure><br>
3136
3137Calls thunk without arguments, returning the result(s) of this call.
3138Before and after are called, also without arguments, as required by the
3139following rules (note that in the absence of calls to continuations
3140captured using call-with-current-continuation the three arguments are
3141called once each, in order). Before is called whenever execution enters
3142the dynamic extent of the call to thunk and after is called whenever it
3143exits that dynamic extent. The dynamic extent of a procedure call is
3144the period between when the call is initiated and when it returns. In
3145Scheme, because of call-with-current-continuation, the dynamic extent
3146of a call may not be a single, connected time period. It is defined as
3147follows:
3148
3149*   The dynamic extent is entered when execution of the body of the
3150    called procedure begins.
3151
3152*   The dynamic extent is also entered when execution is not within the
3153    dynamic extent and a continuation is invoked that was captured
3154    (using call-with-current-continuation) during the dynamic extent.
3155
3156*   It is exited when the called procedure returns.
3157
3158*   It is also exited when execution is within the dynamic extent and a
3159    continuation is invoked that was captured while not within the
3160    dynamic extent.
3161
3162If a second call to dynamic-wind occurs within the dynamic extent of
3163the call to thunk and then a continuation is invoked in such a way that
3164the afters from these two invocations of dynamic-wind are both to be
3165called, then the after associated with the second (inner) call to
3166dynamic-wind is called first.
3167
3168If a second call to dynamic-wind occurs within the dynamic extent of
3169the call to thunk and then a continuation is invoked in such a way that
3170the befores from these two invocations of dynamic-wind are both to be
3171called, then the before associated with the first (outer) call to
3172dynamic-wind is called first.
3173
3174If invoking a continuation requires calling the before from one call to
3175dynamic-wind and the after from another, then the after is called
3176first.
3177
3178The effect of using a captured continuation to enter or exit the
3179dynamic extent of a call to before or after is undefined.  However,
3180in CHICKEN it is safe to do this, and they will execute in the outer
3181dynamic context of the {{dynamic-wind}} form.
3182
3183 (let ((path '())
3184       (c #f))
3185   (let ((add (lambda (s)
3186                (set! path (cons s path)))))
3187     (dynamic-wind
3188       (lambda () (add 'connect))
3189       (lambda ()
3190         (add (call-with-current-continuation
3191                (lambda (c0)
3192                  (set! c c0)
3193                  'talk1))))
3194       (lambda () (add 'disconnect)))
3195     (if (< (length path) 4)
3196         (c 'talk2)
3197         (reverse path))))
3198 
3199                 ===> (connect talk1 disconnect
3200                       connect talk2 disconnect)
3201
3202=== Eval
3203
3204<procedure>(eval expression [environment-specifier])</procedure><br>
3205
3206Evaluates expression in the specified environment and returns its
3207value. Expression must be a valid Scheme expression represented as
3208data, and environment-specifier must be a value returned by one of the
3209three procedures described below. Implementations may extend eval to
3210allow non-expression programs (definitions) as the first argument and
3211to allow other values as environments, with the restriction that eval
3212is not allowed to create new bindings in the environments associated
3213with null-environment or scheme-report-environment.
3214
3215 (eval '(* 7 3) (scheme-report-environment 5))
3216                                                            ===>  21
3217 
3218 (let ((f (eval '(lambda (f x) (f x x))
3219                (null-environment 5))))
3220   (f + 10))
3221                                                            ===>  20
3222
3223The {{environment-specifier}} is optional, and if not provided it
3224defaults to the value of {{(interaction-environment)}}.  This is a
3225CHICKEN extension to R5RS, which, though strictly nonportable, is very
3226common among Scheme implementations.
3227
3228<procedure>(scheme-report-environment version [mutable])</procedure><br>
3229<procedure>(null-environment version [mutable])</procedure><br>
3230
3231Version must be either the exact integer 4 or 5, corresponding to the
3232respective revisions of the Scheme report (the Revised^N Report on
3233Scheme).  Scheme-report-environment returns a specifier for an
3234environment that is empty except for all bindings defined in this
3235report that are either required or both optional and supported by the
3236implementation.  Null-environment returns a specifier for an
3237environment that is empty except for the (syntactic) bindings for all
3238syntactic keywords defined in this report that are either required or
3239both optional and supported by the implementation.
3240
3241The environments specified by scheme-report-environment and
3242null-environment are immutable by default.  In CHICKEN, as an
3243extension to R5RS, an extra {{mutable}} argument can be passed, which
3244makes the environments mutable when non-{{#f}}.  Mutability means new
3245top-level definitions are accepted and the values of existing
3246top-level bindings can be mutated.
3247
3248<procedure>(interaction-environment)</procedure><br>
3249
3250This procedure returns a specifier for the environment that contains
3251implementation-defined bindings, typically a superset of those listed
3252in the report. The intent is that this procedure will return the
3253environment in which the implementation would evaluate expressions
3254dynamically typed by the user.
3255
3256=== Input and output
3257
3258==== Ports
3259
3260Ports represent input and output devices. To Scheme, an input port is a
3261Scheme object that can deliver characters upon command, while an output
3262port is a Scheme object that can accept characters.
3263
3264<procedure>(call-with-input-file string proc [mode ...])</procedure><br>
3265<procedure>(call-with-output-file string proc [mode ...])</procedure><br>
3266
3267String should be a string naming a file, and proc should be a procedure
3268that accepts one argument. For call-with-input-file, the file should
3269already exist; for call-with-output-file, the effect is unspecified if
3270the file already exists. These procedures call proc with one argument:
3271the port obtained by opening the named file for input or output. If the
3272file cannot be opened, an error is signalled. If proc returns, then the
3273port is closed automatically and the value(s) yielded by the proc is
3274(are) returned. If proc does not return, then the port will not be
3275closed automatically unless it is possible to prove that the port will
3276never again be used for a read or write operation.
3277
3278Rationale:   Because Scheme's escape procedures have unlimited
3279extent, it is possible to escape from the current continuation but
3280later to escape back in. If implementations were permitted to close
3281the port on any escape from the current continuation, then it would
3282be impossible to write portable code using both
3283call-with-current-continuation and call-with-input-file or
3284call-with-output-file.
3285
3286Additional {{mode}} arguments can be passed in, which should be any of
3287the keywords {{#:text}}, {{#:binary}} or {{#:append}}.  {{#:text}} and
3288{{#:binary}} indicate the mode in which to open the file (this has an
3289effect on non-UNIX platforms only), while {{#:append}} indicates that
3290instead of truncating the file on open, data written to it should be
3291appended at the end (only for output files).  The extra {{mode}}
3292arguments are CHICKEN extensions to the R5RS standard.
3293
3294<procedure>(input-port? obj)</procedure><br>
3295<procedure>(output-port? obj)</procedure><br>
3296
3297Returns #t if obj is an input port or output port respectively,
3298otherwise returns #f.
3299
3300<procedure>(current-input-port [port])</procedure><br>
3301<procedure>(current-output-port [port])</procedure><br>
3302
3303Returns the current default input or output port.
3304
3305If the optional {{port}} argument is passed, the current input or
3306output port is changed to the provided port.  It can also be used with
3307{{parameterize}} to temporarily bind the port to another value.  This
3308is a CHICKEN extension to the R5RS standard.
3309
3310Note that the default output port is not buffered. Use
3311[[Module (chicken port)#set-buffering-mode!|{{set-buffering-mode!}}]]
3312if you need a different behavior.
3313
3314
3315<procedure>(with-input-from-file string thunk [mode ...])</procedure><br>
3316<procedure>(with-output-to-file string thunk [mode ...])</procedure><br>
3317
3318String should be a string naming a file, and thunk should be a procedure
3319of no arguments. For with-input-from-file, the file should already
3320exist; for with-output-to-file, the effect is unspecified if the file
3321already exists. The file is opened for input or output, an input or
3322output port connected to it is made the default value returned by
3323current-input-port or current-output-port (and is used by (read),
3324(write obj), and so forth), and the thunk is called with no arguments.
3325When the thunk returns, the port is closed and the previous default is
3326restored. With-input-from-file and with-output-to-file return(s) the
3327value(s) yielded by thunk. If an escape procedure is used to escape
3328from the continuation of these procedures, their behavior is
3329implementation dependent.
3330
3331Additional {{mode}} arguments can be passed in, which should be any of
3332the keywords {{#:text}}, {{#:binary}} or {{#:append}}.  {{#:text}} and
3333{{#:binary}} indicate the mode in which to open the file (this has an
3334effect on non-UNIX platforms only), while {{#:append}} indicates that
3335instead of truncating the file on open, data written to it should be
3336appended at the end (only for output files).  The extra {{mode}}
3337arguments are CHICKEN extensions to the R5RS standard.
3338
3339<procedure>(open-input-file filename [mode ...])</procedure><br>
3340
3341Takes a string naming an existing file and returns an input port
3342capable of delivering characters from the file. If the file cannot be
3343opened, an error is signalled.
3344
3345Additional {{mode}} arguments can be passed in, which should be any of
3346the keywords {{#:text}} or {{#:binary}}.  These indicate the mode in
3347which to open the file (this has an effect on non-UNIX platforms
3348only).  The extra {{mode}} arguments are CHICKEN extensions to the
3349R5RS standard.
3350
3351<procedure>(open-output-file filename [mode ...])</procedure><br>
3352
3353Takes a string naming an output file to be created and returns an
3354output port capable of writing characters to a new file by that name.
3355If the file cannot be opened, an error is signalled. If a file with the
3356given name already exists, the effect is unspecified.
3357
3358Additional {{mode}} arguments can be passed in, which should be any of
3359the keywords {{#:text}}, {{#:binary}} or {{#:append}}.  {{#:text}} and
3360{{#:binary}} indicate the mode in which to open the file (this has an
3361effect on non-UNIX platforms only), while {{#:append}} indicates that
3362instead of truncating the file on open, data written to it should be
3363appended at the end.  The extra {{mode}} arguments are CHICKEN
3364extensions to the R5RS standard.
3365
3366<procedure>(close-input-port port)</procedure><br>
3367<procedure>(close-output-port port)</procedure><br>
3368
3369Closes the file associated with port, rendering the port incapable of
3370delivering or accepting characters. These routines have no effect if
3371the file has already been closed. The value returned is unspecified.
3372
3373==== Input
3374
3375<procedure>(read)</procedure><br>
3376<procedure>(read port)</procedure><br>
3377
3378Read converts external representations of Scheme objects into the
3379objects themselves. That is, it is a parser for the nonterminal
3380<datum> (see also "[[#pairs-and-lists|pairs and lists]]"). Read
3381returns the next object parsable from the given input port, updating
3382port to point to the first character past the end of the external
3383representation of the object.
3384
3385If an end of file is encountered in the input before any characters are
3386found that can begin an object, then an end of file object is returned.
3387The port remains open, and further attempts to read will also return an
3388end of file object. If an end of file is encountered after the
3389beginning of an object's external representation, but the external
3390representation is incomplete and therefore not parsable, an error is
3391signalled.
3392
3393The port argument may be omitted, in which case it defaults to the
3394value returned by current-input-port. It is an error to read from a
3395closed port.
3396
3397<procedure>(read-char)</procedure><br>
3398<procedure>(read-char port)</procedure><br>
3399
3400Returns the next character available from the input port, updating the
3401port to point to the following character. If no more characters are
3402available, an end of file object is returned. Port may be omitted, in
3403which case it defaults to the value returned by current-input-port.
3404
3405<procedure>(peek-char)</procedure><br>
3406<procedure>(peek-char port)</procedure><br>
3407
3408Returns the next character available from the input port, without
3409updating the port to point to the following character. If no more
3410characters are available, an end of file object is returned. Port may
3411be omitted, in which case it defaults to the value returned by
3412current-input-port.
3413
3414Note:   The value returned by a call to peek-char is the same as
3415the value that would have been returned by a call to read-char with
3416the same port. The only difference is that the very next call to
3417read-char or peek-char on that port will return the value returned
3418by the preceding call to peek-char. In particular, a call to
3419peek-char on an interactive port will hang waiting for input
3420whenever a call to read-char would have hung.
3421
3422<procedure>(eof-object? obj)</procedure><br>
3423
3424Returns #t if obj is an end of file object, otherwise returns #f. The
3425precise set of end of file objects will vary among implementations, but
3426in any case no end of file object will ever be an object that can be
3427read in using read.
3428
3429<procedure>(char-ready?)</procedure><br>
3430<procedure>(char-ready? port)</procedure><br>
3431
3432Returns #t if a character is ready on the input port and returns #f
3433otherwise. If char-ready returns #t then the next read-char operation
3434on the given port is guaranteed not to hang. If the port is at end of
3435file then char-ready? returns #t. Port may be omitted, in which case it
3436defaults to the value returned by current-input-port.
3437
3438Rationale:   Char-ready? exists to make it possible for a program
3439to accept characters from interactive ports without getting stuck
3440waiting for input. Any input editors associated with such ports
3441must ensure that characters whose existence has been asserted by
3442char-ready? cannot be rubbed out. If char-ready? were to return #f
3443at end of file, a port at end of file would be indistinguishable
3444from an interactive port that has no ready characters.
3445
3446==== Output
3447
3448<procedure>(write obj)</procedure><br>
3449<procedure>(write obj port)</procedure><br>
3450
3451Writes a written representation of obj to the given port. Strings that
3452appear in the written representation are enclosed in doublequotes, and
3453within those strings backslash and doublequote characters are escaped
3454by backslashes. Character objects are written using the #\ notation.
3455Write returns an unspecified value. The port argument may be omitted,
3456in which case it defaults to the value returned by current-output-port.
3457
3458<procedure>(display obj)</procedure><br>
3459<procedure>(display obj port)</procedure><br>
3460
3461Writes a representation of obj to the given port. Strings that appear
3462in the written representation are not enclosed in doublequotes, and no
3463characters are escaped within those strings. Character objects appear
3464in the representation as if written by write-char instead of by write.
3465Display returns an unspecified value. The port argument may be omitted,
3466in which case it defaults to the value returned by current-output-port.
3467
3468Rationale:   Write is intended for producing machine-readable
3469output and display is for producing human-readable output.
3470Implementations that allow "slashification" within symbols will
3471probably want write but not display to slashify funny characters in
3472symbols.
3473
3474<procedure>(newline)</procedure><br>
3475<procedure>(newline port)</procedure><br>
3476
3477Writes an end of line to port. Exactly how this is done differs from
3478one operating system to another. Returns an unspecified value. The port
3479argument may be omitted, in which case it defaults to the value
3480returned by current-output-port.
3481
3482<procedure>(write-char char)</procedure><br>
3483<procedure>(write-char char port)</procedure><br>
3484
3485Writes the character char (not an external representation of the
3486character) to the given port and returns an unspecified value. The port
3487argument may be omitted, in which case it defaults to the value
3488returned by current-output-port.
3489
3490==== System interface
3491
3492Questions of system interface generally fall outside of the domain of
3493this report. However, the following operations are important enough to
3494deserve description here.
3495
3496<procedure>(load filename [evalproc])</procedure><br>
3497
3498Filename should be a string naming an existing file containing Scheme
3499source code. The load procedure reads expressions and definitions from
3500the file and evaluates them sequentially. It is unspecified whether the
3501results of the expressions are printed. The load procedure does not
3502affect the values returned by current-input-port and
3503current-output-port. Load returns an unspecified value.
3504
3505CHICKEN offers a few extensions to the R5RS definition of {{load}}:
3506
3507* The {{filename}} may also be an input port.
3508* The expressions which are read one by one from the source file are passed to the procedure indicated by the extra optional {{evalproc}} argument, which defaults to {{eval}}.
3509* On platforms that support it (currently BSD, Haiku, MacOS X, Linux, Solaris, and Windows), {{load}} can be used to load shared objects.
3510
3511Example for loading compiled programs:
3512
3513 % cat x.scm
3514 (define (hello) (print "Hello!"))
3515 % csc -s x.scm
3516 % csi -q
3517 #;1> (load "x.so")
3518 ; loading x.so ...
3519 #;2> (hello)
3520 Hello!
3521 #;3>
3522
3523There are some limitations and caveats to the CHICKEN extensions you
3524need to be aware of:
3525
3526* The second argument to {{load}} is ignored when loading compiled code.
3527* If source code is loaded from a port, then that port is closed after all expressions have been read.
3528* A compiled file can only be loaded once. Subsequent attempts to load the same file have no effect.
3529
3530
3531<procedure>(transcript-on filename)</procedure><br>
3532<procedure>(transcript-off)</procedure><br>
3533
3534(These procedures are not implemented in CHICKEN.)
3535
3536Filename must be a string naming an output file to be created. The
3537effect of transcript-on is to open the named file for output, and to
3538cause a transcript of subsequent interaction between the user and the
3539Scheme system to be written to the file. The transcript is ended by a
3540call to transcript-off, which closes the transcript file. Only one
3541transcript may be in progress at any time, though some implementations
3542may relax this restriction. The values returned by these procedures are
3543unspecified.
3544
3545---
3546Previous: [[Included modules]]
3547
3548Next: [[Module r5rs]]
Trap